<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aryan Chauhan on Medium]]></title>
        <description><![CDATA[Stories by Aryan Chauhan on Medium]]></description>
        <link>https://medium.com/@unknown0149?source=rss-6a30a2fdc261------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wYDsOKcWVL_O6emA_lMREA.png</url>
            <title>Stories by Aryan Chauhan on Medium</title>
            <link>https://medium.com/@unknown0149?source=rss-6a30a2fdc261------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:16:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@unknown0149/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Beyond the SOS Button: Building an Emergency Response Workflow for Tourist Safety]]></title>
            <link>https://medium.com/@unknown0149/beyond-the-sos-button-building-an-emergency-response-workflow-for-tourist-safety-04d507b18814?source=rss-6a30a2fdc261------2</link>
            <guid isPermaLink="false">https://medium.com/p/04d507b18814</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Aryan Chauhan]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 14:52:33 GMT</pubDate>
            <atom:updated>2026-11-27T14:52:33.445Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How backend APIs, authentication, MongoDB, and Socket.IO work together to turn a tourist’s emergency signal into an incident that can be monitored and handled.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dg0ybIXk7kLrOzNhtkvnYw.png" /></figure><p>Imagine a tourist exploring a city alone. Suddenly, they find themselves in an unsafe situation. They open the application and press the Emergency SOS button.</p><p>What should happen next?</p><p>The application needs to capture the tourist’s identity and location, create an emergency record, notify the relevant authorities, and allow an officer to acknowledge and resolve the incident.</p><p>A button that simply displays <strong>“Emergency Alert Sent”</strong> is not enough. A real safety workflow needs a reliable process behind it.</p><p>That is the engineering problem explored in the <strong>Tourist Safety Platform</strong> project. Alongside its location monitoring and risk-assessment features, the repository contains a backend alert workflow built using Node.js, Express, TypeScript, MongoDB, Mongoose, and Socket.IO.</p><p>Let’s walk through the architecture and examine how these components fit together.</p><h3>1. An emergency alert is more than a notification</h3><p>One of the important design decisions in an emergency system is treating an alert as a persistent incident record rather than a temporary message.</p><p>The project defines three primary alert types:</p><ul><li><strong>Panic:</strong> A tourist manually triggers an emergency alert.</li><li><strong>Geo-fence:</strong> A tourist enters a monitored or restricted area.</li><li><strong>Anomaly:</strong> Unusual activity or behaviour is identified.</li></ul><p>Each aert also contains information such as:</p><ul><li>Tourist ID</li><li>Alert type</li><li>GPS coordinates</li><li>Timestamp</li><li>Severity</li><li>Description</li><li>Current status</li><li>Acknowledging officer</li><li>Resolution details</li></ul><p>This information is defined in the project’s Alert Mongoose model.</p><p>For example, a panic alert might look conceptually like this:</p><pre>{<br>  &quot;touristId&quot;: &quot;tourist_123&quot;,<br>  &quot;type&quot;: &quot;panic&quot;,<br>  &quot;severity&quot;: &quot;critical&quot;,<br>  &quot;location&quot;: {<br>    &quot;latitude&quot;: 28.6139,<br>    &quot;longitude&quot;: 77.2090<br>  },<br>  &quot;status&quot;: &quot;active&quot;,<br>  &quot;description&quot;: &quot;Emergency alert triggered by tourist&quot;<br>}</pre><p>The benefit of storing an alert is that the system can retrieve it later, track its progress, and identify which officer acknowledged or resolved it.</p><p>A notification may disappear from a screen. An incident record should remain available for investigation and auditing.</p><h3>2. How the backend receives an SOS request</h3><p>The backend exposes an endpoint for triggering emergency alerts:</p><p>POST /api/alerts/trigger-alert</p><p>The route is defined in backend/routes/alerts.ts, and its controller is implemented in backend/controllers/alerts.ts.</p><p>When a request arrives, the controller extracts information such as:</p><ul><li>touristId</li><li>latitude</li><li>longitude</li><li>type</li><li>description</li><li>severity</li></ul><p>But the backend does not immediately create an alert. It performs several checks first.</p><p><strong>Step 1: Validate the input</strong></p><p>The controller checks that the required tourist ID and coordinates are present.</p><p><strong>Step 2: Validate the coordinates</strong></p><p>The coordinates are passed to a validation utility to ensure that the supplied latitude and longitude are within valid geographic ranges.</p><p><strong>Step 3: Validate the alert type</strong></p><p>Only the supported types are accepted: panic, geo-fence, and anomaly.</p><p><strong>Step 4: Verify the tourist</strong></p><p>The backend searches for the tourist in MongoDB and checks that the account exists and is active.</p><p><strong>Step 5: Check authorization</strong></p><p>A tourist must not be allowed to create an alert on behalf of another tourist. The controller compares the authenticated user’s ID with the requested tourist ID.</p><p>These checks matter because the frontend should never be trusted to decide who is allowed to create or access an emergency record.</p><h3>3. Authentication: how does the backend know who sent the request?</h3><p>The project uses JWT-based authentication.</p><p>When a request reaches the authentication middleware, the backend extracts the token from the authorization header and verifies it.</p><p>It then retrieves the corresponding user from the database. The middleware supports two user types:</p><ul><li>Tourist</li><li>Police</li></ul><p>It also checks whether the account is active before attaching the authenticated user’s information to the Express request.</p><p>This allows other controllers to make decisions based on the identity and role of the requester.</p><p>For example, a tourist can retrieve their own alerts, while police users can access the wider alert-monitoring functionality.</p><p>This separation is especially important in a system handling personal information and live location data.</p><h3>4. Saving the alert before broadcasting it</h3><p>After the validations are successful, the controller creates an Alert document and saves it to MongoDB.</p><p>For a panic alert, the severity is automatically set to critical.</p><p>The controller also records the location, timestamp, description, and metadata.</p><p>This creates a persistent record before the system attempts its real-time notification steps.</p><p>The backend then attempts to calculate the tourist’s updated safety score. The result can be sent through Socket.IO as an additional update.</p><p>Importantly, a failure during safety-score calculation does not automatically cancel the emergency alert. The controller catches that error and continues.</p><p>That is a useful design principle: <strong>an optional analytics operation should not prevent the creation of a critical emergency record.</strong></p><h3>5. Why Socket.IO is used</h3><p>Saving an alert in MongoDB does not automatically make it appear on another user’s screen.</p><p>Without real-time communication, the police dashboard would need to repeatedly request updated alert information from the backend.</p><p>The project uses Socket.IO to communicate between connected clients and the server.</p><p>The socket service verifies the user’s JWT during connection establishment and checks that the corresponding user is active.</p><p>After authentication, users are placed into rooms:</p><ul><li>Individual user rooms</li><li>The shared police_dashboard room for police users</li></ul><p>This makes it possible to send updates to connected police dashboards without sending every message to every application user.</p><h3>What happens when a panic alert is triggered?</h3><p>The controller calls the specialized panic-alert broadcasting method.</p><p>The socket service then:</p><ol><li>Sends a panic_alert event to connected police users.</li><li>Sends a panic_alert_acknowledged event to the tourist, if connected.</li><li>Broadcasts a dashboard_panic_alert event to the police dashboard room.</li></ol><p>The dashboard event includes information intended to help the interface highlight the incident, show an emergency modal, and focus attention on the tourist’s location.</p><p>There are also separate events for geofence and anomaly alerts.</p><p>For example, a geofence alert can communicate the zone name, risk level, location, and whether police notification is required.</p><p>This is more useful than sending a generic message saying that an emergency occurred. The receiving dashboard gets context that can help an officer understand the situation.</p><p>One important distinction: a Socket.IO event being delivered to connected police clients does not prove that an officer has physically received or responded to the incident. It is a real-time communication mechanism, not a complete emergency dispatch service.</p><h3>6. What happens after an officer receives the alert?</h3><p>Creating an alert is only the beginning. An emergency system also needs to track what happens afterward.</p><p>The repository defines an alert lifecycle with these statuses:</p><ul><li>active</li><li>acknowledged</li><li>resolved</li><li>false-alarm</li></ul><p>The backend exposes two important endpoints.</p><p><strong>Acknowledge an alert</strong></p><p>PUT /api/alerts/:alertId/acknowledge</p><p>This operation is restricted to police users. It records the officer who acknowledged the incident and the acknowledgement timestamp. It can also store notes.</p><p><strong>Resolve an alert</strong></p><p>PUT /api/alerts/:alertId/resolve</p><p>This operation records the officer responsible for resolving the incident, the resolution timestamp, and any notes.</p><p>The Alert model also defines virtual fields for calculating response time and resolution time.</p><p>For example:</p><ul><li>Response time = acknowledgement time − alert creation time.</li><li>Resolution time = resolution time − alert creation time.</li></ul><p>These measurements can eventually help evaluate how quickly emergency incidents are handled.</p><p>A useful extension would be to analyse these metrics by alert severity, location, and time of day.</p><h3>7. How are emergency contacts notified?</h3><p>The alert controller also prepares an emergency message containing the tourist’s name, location, alert type, and timestamp.</p><p>It then iterates through the tourist’s emergency contacts.</p><p>However, there is an important implementation detail here.</p><p>The current code contains placeholder behaviour for SMS and email notifications. It logs the intended messages to the console and constructs success-like results, while comments indicate that actual SMS and email service integrations are still required.</p><p>Therefore, this part should be described as a notification workflow that is prepared for integration, not as a fully operational SMS or email delivery system.</p><p>For production use, an external messaging provider would need to be integrated, and delivery failures would need to be handled through retries and monitoring.</p><p>Being transparent about this distinction is important when presenting the project.</p><h3>8. The difference between the backend workflow and the dashboard demo</h3><p>A particularly important detail appears when examining the frontend.</p><p>The tourist dashboard contains an Emergency SOS button. Its current click handler switches the interface into emergency mode and adds an alert to local React state.</p><p>It also creates a simulated police-response message after a short timeout.</p><p>Similarly, the police dashboard initializes example tourist and emergency-alert data. It periodically generates sample alerts, and its acknowledgement and resolution handlers update local component state.</p><p>This means the dashboard pages contain demonstration behaviour that is separate from the backend’s persistent alert APIs.</p><p>The repository has backend functionality for creating, retrieving, acknowledging, and resolving alerts, but the inspected dashboard flows do not demonstrate a fully connected end-to-end dispatch process.</p><p>This distinction is worth understanding: <strong>a working interface, a functioning API, and a fully integrated production system are three different levels of implementation.</strong></p><h3>9. What would make this system production-ready?</h3><p>The existing implementation provides a foundation, but emergency software needs particularly careful engineering.</p><p>Here are some improvements worth prioritising.</p><p><strong>1. Connect the dashboards to the backend</strong></p><p>The SOS button should call the actual alert API. The police dashboard should retrieve stored alerts and subscribe to authenticated Socket.IO events instead of relying on sample data.</p><p><strong>2. Make alert status transitions consistent</strong></p><p>There is a small inconsistency in the current backend. The acknowledgement controller records acknowledgedBy and acknowledgedAt, but does not explicitly change status to acknowledged, even though the model supports that status.</p><p>The active-alert query also uses a resolved field, whereas the Alert schema defines a status field. These should be aligned and covered by tests.</p><p><strong>3. Prevent duplicate acknowledgements</strong></p><p>Imagine two officers opening the same emergency alert at almost the same time.</p><p>The backend should use a guarded database update so that only an eligible officer can claim the incident. Otherwise, multiple officers may believe they are responsible for the same alert.</p><p><strong>4. Add reliable notification delivery</strong></p><p>Socket connections can drop, and messaging providers can fail. A production system should use retry mechanisms, delivery tracking, and a persistent notification queue.</p><p>It should also distinguish between an event being emitted, an event reaching a client, and an officer actually acknowledging the incident.</p><p><strong>5. Maintain an audit trail</strong></p><p>Every important action should be recorded: who acknowledged an alert, when it happened, what notes were added, and who resolved the incident.</p><p>Location data and emergency information should also have appropriate access controls and retention policies.</p><p><strong>6. Test failure scenarios</strong></p><p>The system should be tested when a tourist loses connectivity, GPS coordinates are unavailable, multiple officers try to acknowledge one alert, or a notification provider fails.</p><p>Emergency workflows should be designed around failure, not just the ideal sequence of events.</p><h3>Conclusion</h3><p>Building a tourist safety application involves much more than displaying a map or adding an SOS button.</p><p>The system must establish identity, validate requests, preserve emergency records, communicate updates, and provide a way to track how each incident is handled.</p><p>The Tourist Safety Platform repository demonstrates several important pieces of that architecture: JWT authentication, MongoDB-backed alert records, Express endpoints, Socket.IO event broadcasting, and an acknowledgement and resolution workflow.</p><p>At the same time, examining the implementation reveals the difference between a prototype and a production-ready emergency system. The frontend still contains simulated responses, external notification delivery is not fully integrated, and some status-handling logic needs refinement.</p><p>For a software engineering project, these details are just as valuable as the features themselves. They show not only how a system is designed, but also how to evaluate its reliability and identify the engineering work needed to take it further.</p><p><strong>Technologies discussed:</strong> Node.js, Express.js, TypeScript, MongoDB, Mongoose, JWT, Socket.IO, Next.js, React.</p><p><strong>Suggested Medium tags:</strong> Software Engineering · Backend Development · Node.js · System Design · Real-Time Applications</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04d507b18814" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Spring AI with Spring Boot: Building an AI-Powered Help Desk, RAG, Tool Calling, MCP and…]]></title>
            <link>https://medium.com/@unknown0149/exploring-spring-ai-with-spring-boot-building-an-ai-powered-help-desk-rag-tool-calling-mcp-and-ee1a6cf0e29c?source=rss-6a30a2fdc261------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1a6cf0e29c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Aryan Chauhan]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 14:11:32 GMT</pubDate>
            <atom:updated>2026-11-27T14:14:18.843Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Spring AI with Spring Boot: Building an AI-Powered Help Desk, RAG, Tool Calling, MCP and More</h3><h3>A practical deep dive into integrating Large Language Models into Java applications using Spring AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOx-IT7e3overmfIM_GRUA.png" /></figure><p>Artificial Intelligence is changing the way we build software applications. Traditional applications follow predefined business logic, whereas AI-powered applications can understand natural-language requests, maintain conversational context, retrieve relevant information, and interact with external services.</p><p>As a Java and Spring Boot developer, I wanted to explore how these capabilities could be integrated into a familiar backend ecosystem.</p><p>This project is a hands-on exploration of <strong>Spring AI and its integration with Spring Boot</strong>, covering everything from basic LLM communication to Retrieval-Augmented Generation (RAG), conversational memory, AI tool calling, Model Context Protocol (MCP), and multimodal AI.</p><p>The repository also contains an integrated AI Help Desk application that demonstrates how these concepts can work together in a practical use case.</p><p><strong>GitHub Repository:</strong> <a href="https://github.com/unknown0149/Spring_ai_Ecommerce_Platform">Spring_ai_Ecommerce_Platform</a></p><h3>1. What is Spring AI?</h3><p>Before looking at the implementation, let’s understand the technology behind the project.</p><p>Spring AI is a framework that helps Java developers integrate AI models into Spring applications using familiar Spring programming patterns.</p><p>Normally, when integrating an AI provider into a Java application, we might need to manually manage HTTP requests, API authentication, request payloads, response parsing, and model-specific configurations.</p><p>Spring AI provides abstractions that simplify these interactions.</p><p>Some important capabilities explored in this repository include:</p><ul><li>ChatClient for communicating with language models.</li><li>Prompt templates for controlling model behaviour.</li><li>Advisors for modifying and monitoring AI interactions.</li><li>Chat Memory for maintaining conversation history.</li><li>Vector Stores for semantic document retrieval.</li><li>RAG for generating responses using external knowledge.</li><li>Tool Calling for allowing models to interact with application functionality.</li><li>MCP integration for connecting models to external tools.</li><li>Image generation and audio transcription.</li></ul><p>The central abstraction used throughout the project is ChatClient.</p><h3>2. Project Overview</h3><p>Rather than being a single Spring Boot application, the repository contains several independent Spring AI experiments.</p><p>The major areas are:</p><p>ModulePurposechatclient-apiBasic ChatClient integration and prompt handlingspring-ai-openaiOpenAI and Ollama model integrationspring-ai-ollamLocal LLM integration using Ollamaboot-gemini-appGoogle Gemini integrationadvisor_appCustom advisors and token usage monitoringmemory_appPersistent conversational memoryrag_appBasic Retrieval-Augmented Generationadvance_ragAdvanced document retrieval and query transformationtool-calling-exampleExternal tools such as weather and date/timemcp-appModel Context Protocol client integrationspring_ai_mediaImage generation and audio transcriptionhelp-desk-backendAI-powered ticket management backendhelpdesk-frontendReact-based chat interface</p><p>Each Maven application demonstrates a particular Spring AI capability.</p><p>The Help Desk application is the most complete user-facing example because it combines a React interface, Spring Boot, an LLM, database operations, and conversation memory.</p><h3>3. High-Level Architecture</h3><p>The Help Desk application follows a frontend-backend architecture.</p><p>The frontend communicates with a Spring Boot REST API. The backend coordinates the conversation with the AI model and exposes application functionality through Spring AI tools.</p><p>The high-level interaction looks like this:</p><pre>USER<br>                    |<br>                    v<br>             REACT FRONTEND<br>                    |<br>                    | HTTP POST<br>                    v<br>           SPRING BOOT BACKEND<br>                    |<br>                    v<br>              AI CONTROLLER<br>                    |<br>                    v<br>                AI SERVICE<br>                    |<br>                    v<br>                CHAT CLIENT<br>                    |<br>                    v<br>             LARGE LANGUAGE MODEL<br>                    |<br>          +---------+----------+<br>          |                    |<br>          v                    v<br>    TICKET DATABASE       EMAIL TOOL<br>       TOOL                  |<br>          |                  |<br>          v                  v<br>    TICKET SERVICE       CONSOLE LOG<br>          |<br>          v<br>    SPRING DATA JPA<br>          |<br>          v<br>        MYSQL</pre><pre>     CONVERSATION MEMORY<br>          |<br>          v<br>    JDBC MEMORY REPOSITORY<br>          |<br>          v<br>        MYSQL</pre><p>The important idea is that the LLM is not directly responsible for database operations. Instead, the application provides controlled tools that allow the model to request specific operations.</p><p>Let’s understand the implementation.</p><h3>4. Backend Development with Spring Boot</h3><p>The backend is developed using Java and Spring Boot.</p><p>The main technologies include:</p><ul><li>Spring Boot</li><li>Spring AI</li><li>Spring Web</li><li>Spring Data JPA</li><li>Hibernate</li><li>MySQL</li><li>Project Lombok</li><li>Reactor</li></ul><p>The backend is divided into separate responsibilities.</p><h3>4.1 AI Controller</h3><p>The controller exposes the Help Desk API.</p><p>The main endpoint is:</p><pre>@RestController<br>@RequestMapping(&quot;/api/v1/helpdesk&quot;)<br>@RequiredArgsConstructor<br>@CrossOrigin(&quot;http://localhost:5173&quot;)<br>public class AiController {</pre><pre>    private final AIService service;</pre><pre>    @PostMapping<br>    public ResponseEntity&lt;String&gt; getResponse(<br>            @RequestBody String query,<br>            @RequestHeader(&quot;ConversationId&quot;) String conversationId) {</pre><pre>        return ResponseEntity.ok(<br>            service.getResponseFromAssistant(<br>                query,<br>                conversationId<br>            )<br>        );<br>    }<br>}</pre><p>The endpoint accepts two important pieces of information:</p><ol><li>The user’s message in the request body.</li><li>A ConversationId in the HTTP request header.</li></ol><p>Why is the conversation ID important?</p><p>Imagine a user sends these messages:</p><pre>User: My laptop is not working.</pre><pre>Assistant: Can you tell me what happens<br>when you press the power button?</pre><pre>User: Nothing happens.</pre><p>The AI should understand that the second message is related to the first one.</p><p>The conversation ID helps associate messages with the correct conversation.</p><p>The controller forwards the request to the AI service rather than implementing the AI logic itself.</p><h3>4.2 AI Service</h3><p>The AIService class is responsible for communicating with the language model.</p><p>It uses Spring AI’s ChatClient.</p><p>The important implementation looks like this:</p><pre>public String getResponseFromAssistant(<br>        String query,<br>        String conversationId) {</pre><pre>    return this.chatClient<br>            .prompt()</pre><pre>            .advisors(advisorSpec -&gt;<br>                advisorSpec.param(<br>                    ChatMemory.CONVERSATION_ID,<br>                    conversationId<br>                )<br>            )</pre><pre>            .tools(ticketDatabaseTool, emailTool)</pre><pre>            .system(systemPromptResource)</pre><pre>            .user(query)</pre><pre>            .call()</pre><pre>            .content();<br>}</pre><p>There are several important operations happening here.</p><p><strong>.prompt()</strong></p><p>Starts the prompt-building process.</p><p><strong>.advisors()</strong></p><p>Provides the conversation ID so that the appropriate conversation history can be retrieved.</p><p><strong>.tools()</strong></p><p>Makes application functionality available to the language model.</p><p><strong>.system()</strong></p><p>Provides the system instructions that define how the Help Desk assistant should behave.</p><p><strong>.user()</strong></p><p>Passes the user’s actual question.</p><p><strong>.call()</strong></p><p>Executes the model interaction.</p><p><strong>.content()</strong></p><p>Extracts the generated response.</p><p>This is one of the most important concepts in the project: Spring AI provides a structured way to combine prompts, memory, advisors, and tools into a single model interaction.</p><h3>5. Designing the AI Assistant with System Prompts</h3><p>A language model does not automatically know the business rules of an application.</p><p>For example, a normal language model does not inherently know:</p><ul><li>How a support ticket should be created.</li><li>Which ticket priorities are available.</li><li>What information must be collected from a user.</li><li>How an existing ticket should be updated.</li><li>When the assistant should check for an existing ticket.</li></ul><p>These instructions are provided through the system prompt.</p><p>The project stores its Help Desk instructions in:</p><pre>help-desk-backend/<br>    src/main/resources/<br>        helpdesk-system.st</pre><p>The assistant is instructed to behave as a professional support assistant named Liza.</p><p>Its responsibilities include:</p><ol><li>Understanding the user’s problem.</li><li>Asking clarifying questions.</li><li>Identifying the issue category.</li><li>Determining the priority.</li><li>Checking for existing tickets.</li><li>Creating new tickets when appropriate.</li><li>Updating existing ticket information.</li><li>Providing troubleshooting guidance.</li></ol><p>For example, when a user reports a problem:</p><pre>User:<br>My laptop is not turning on.</pre><p>The assistant should first understand the issue and collect the required information.</p><p>It may ask for an email address, clarify the symptoms, and determine the issue priority.</p><p>After gathering sufficient information, it can request the appropriate database operation through its available tools.</p><p>This separation is useful because it keeps conversational behaviour in the prompt and business operations in the backend.</p><h3>6. Implementing Tool Calling with Spring AI</h3><p>One of the most interesting features demonstrated by the project is AI tool calling.</p><p>A language model can generate text, but it cannot directly execute Java methods or modify a database.</p><p>Tool calling bridges this gap.</p><p>The application provides certain Java methods to the model and describes what each method does.</p><p>Spring AI uses these descriptions to make tools available during model interactions.</p><p>The Help Desk application has two important tool components.</p><h3>6.1 TicketDatabaseTool</h3><p>This class provides database-related operations to the AI assistant.</p><p>It contains methods for:</p><ul><li>Creating a ticket.</li><li>Retrieving a ticket using an email address.</li><li>Updating a ticket.</li><li>Retrieving the current system time.</li></ul><p>For example:</p><pre>@Component<br>@RequiredArgsConstructor<br>public class TicketDatabaseTool {</pre><pre>    private final TicketService ticketService;</pre><pre>    @Tool(description =<br>        &quot;This tool helps to create new ticket in database.&quot;)<br>    public Ticket createTicketTool(<br>            @ToolParam(description =<br>                &quot;Ticket fields required to create new ticket&quot;)<br>            Ticket ticket) {</pre><pre>        return ticketService.createTicket(ticket);<br>    }<br>}</pre><p>The @Tool annotation exposes the Java method to Spring AI as a tool.</p><p>The @ToolParam annotation provides additional information about its parameters.</p><p>Consider this interaction:</p><pre>User:<br>My internet connection is not working.</pre><pre>Assistant:<br>I understand. Could you please provide<br>your registered email address?</pre><pre>User:<br>user@example.com</pre><pre>Assistant:<br>Could you describe when the issue started?</pre><p>After gathering the required information, the model can request ticket creation.</p><p>The application then invokes the corresponding Java method.</p><p>The actual database operation is performed by the backend, not by the language model itself.</p><h3>6.2 EmailTool</h3><p>The project also defines an email-related tool.</p><p>It is intended to notify the support team when a new ticket is created.</p><p>However, the current implementation only prints the email address and message to the application console. It does not yet integrate an actual email delivery provider.</p><p>This is an important distinction between a tool’s intended purpose and its current implementation.</p><h3>7. Database Design with Spring Data JPA</h3><p>The Help Desk backend uses MySQL for ticket storage.</p><p>The central entity is Ticket.</p><p>It represents a support request submitted by a user.</p><p>The entity contains fields such as:</p><pre>@Entity<br>@Table(name = &quot;help_desk_tickets&quot;)<br>@Getter<br>@Setter<br>@Builder<br>@AllArgsConstructor<br>@NoArgsConstructor<br>public class Ticket implements Serializable {</pre><pre>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;</pre><pre>    @Lob<br>    private String summary;</pre><pre>    @Enumerated(EnumType.STRING)<br>    private Priority priority;</pre><pre>    private String category;</pre><pre>    @Column(length = 1000)<br>    private String description;</pre><pre>    @Column(unique = true)<br>    private String email;</pre><pre>    private LocalDateTime createdOn;<br>    private LocalDateTime updatedOn;</pre><pre>    @Enumerated(EnumType.STRING)<br>    private Status status;<br>}</pre><p>The priority is represented using an enum:</p><pre>public enum Priority {<br>    LOW, MEDIUM, HIGH, URGENT<br>}</pre><p>The status currently contains:</p><pre>public enum Status {<br>    OPEN, CLOSED, RESOLVED<br>}</pre><p>The entity also uses lifecycle methods:</p><pre>@PrePersist<br>void preSave() {<br>    if (this.createdOn == null) {<br>        this.createdOn = LocalDateTime.now();<br>    }</pre><pre>    this.updatedOn = LocalDateTime.now();<br>}</pre><p>This automatically records creation and update timestamps when the entity is persisted.</p><h3>Repository Layer</h3><p>The repository extends Spring Data JPA’s JpaRepository.</p><pre>public interface TicketRepository<br>        extends JpaRepository&lt;Ticket, Long&gt; {</pre><pre>    Optional&lt;Ticket&gt; findByEmail(String email);<br>}</pre><p>This provides standard database operations without manually writing SQL queries for common CRUD operations.</p><h3>Service Layer</h3><p>The TicketService contains the business operations.</p><pre>@Transactional<br>public Ticket createTicket(Ticket ticket) {<br>    ticket.setId(null);<br>    return ticketRepository.save(ticket);<br>}</pre><p>Similarly, existing tickets can be retrieved and updated through the repository.</p><p>This creates a clean separation:</p><pre>TicketDatabaseTool<br>        |<br>        v<br>   TicketService<br>        |<br>        v<br> TicketRepository<br>        |<br>        v<br>      MySQL</pre><h3>8. Conversational Memory</h3><p>A chatbot without memory treats every request as an independent interaction.</p><p>This creates a problem.</p><p>Suppose a user sends:</p><pre>User: I have a problem with my laptop.</pre><pre>Assistant: What is happening?</pre><pre>User: It shuts down after five minutes.</pre><p>Without memory, the model might not understand what “it” refers to.</p><p>Conversational memory solves this problem by providing previous messages as context.</p><p>The project configures memory using:</p><ul><li>JdbcChatMemoryRepository</li><li>MessageWindowChatMemory</li><li>MessageChatMemoryAdvisor</li></ul><p>The configuration looks like this:</p><pre>var chatMemory = MessageWindowChatMemory.builder()<br>        .chatMemoryRepository(jdbcChatMemoryRepository)<br>        .maxMessages(15)<br>        .build();</pre><p>This configuration maintains a message window of up to 15 messages.</p><p>The JDBC repository allows conversation history to be stored using a relational database.</p><p>The memory advisor is attached to the ChatClient:</p><pre>return builder<br>    .defaultSystem(<br>        &quot;Summarize the response within 400 words.&quot;<br>    )<br>    .defaultAdvisors(<br>        new SimpleLoggerAdvisor(),<br>        MessageChatMemoryAdvisor.builder(chatMemory).build()<br>    )<br>    .build();</pre><p>When the application receives a conversation ID, Spring AI uses it to retrieve the corresponding conversation context.</p><p>This allows the assistant to maintain continuity across multiple requests.</p><h3>9. Understanding RAG — Retrieval-Augmented Generation</h3><p>A language model generates answers using the knowledge available to it and the information provided in its current context.</p><p>But what happens when an application needs to answer questions using its own documents?</p><p>For example:</p><pre>User:<br>What is the refund policy mentioned<br>in our company documentation?</pre><p>The model may not know the answer.</p><p>Retrieval-Augmented Generation solves this problem by retrieving relevant information from an external knowledge source and providing it to the model.</p><p>The repository contains both basic and advanced RAG experiments.</p><h3>9.1 Basic RAG</h3><p>The basic RAG application uses:</p><ul><li>Spring AI</li><li>MariaDB Vector Store</li><li>Embeddings</li><li>Vector similarity retrieval</li><li>RetrievalAugmentationAdvisor</li></ul><p>The general workflow is:</p><pre>DOCUMENTS<br>              |<br>              v<br>        TEXT CHUNKING<br>              |<br>              v<br>          EMBEDDINGS<br>              |<br>              v<br>        VECTOR DATABASE<br>              |<br>              |<br>User Query |<br>     |     |<br>     v     |<br>  EMBEDDING |<br>     |     |<br>     v     |<br> VECTOR SEARCH<br>     |<br>     v<br>RELEVANT DOCUMENTS<br>     |<br>     v<br>RETRIEVAL AUGMENTATION<br>     |<br>     v<br>      CHAT MODEL<br>     |<br>     v<br>  FINAL RESPONSE</pre><p>The idea is to retrieve documents related to the user’s question before generating the answer.</p><p>The implementation uses VectorStoreDocumentRetriever.</p><p>An important configuration is:</p><pre>var advisor = RetrievalAugmentationAdvisor.builder()<br>        .documentRetriever(<br>            VectorStoreDocumentRetriever.builder()<br>                .vectorStore(this.vectorStore)<br>                .topK(3)<br>                .similarityThreshold(0.5)<br>                .build()<br>        )<br>        .queryAugmenter(<br>            ContextualQueryAugmenter.builder()<br>                .allowEmptyContext(true)<br>                .build()<br>        )<br>        .build();</pre><p>Here:</p><ul><li>topK(3) requests up to three relevant documents.</li><li>similarityThreshold(0.5) configures the minimum similarity threshold.</li><li>ContextualQueryAugmenter adds retrieved context to the query before generation.</li></ul><p>The resulting advisor is attached to the ChatClient.</p><h3>9.2 Advanced RAG</h3><p>The advanced RAG application explores additional retrieval and query processing techniques.</p><p>It contains document loaders for JSON and PDF files.</p><p>The JSON loader uses JsonReader, while the PDF loader uses PagePdfDocumentReader.</p><p>The documents are passed through a text-splitting component before being added to the vector store.</p><p>The advanced retrieval workflow also demonstrates:</p><p><strong>Query rewriting</strong></p><p>Transforms the user’s question into a form more suitable for retrieval.</p><p><strong>Query expansion</strong></p><p>Generates multiple alternative search queries to improve the chance of finding relevant information.</p><p>The project configures multiple queries through MultiQueryExpander.</p><p><strong>Query translation</strong></p><p>Demonstrates translating a query into Hindi before retrieval.</p><p><strong>Document retrieval</strong></p><p>Uses vector similarity to find relevant information.</p><p><strong>Document joining</strong></p><p>Combines retrieved documents before they are passed to the language model.</p><p><strong>Contextual augmentation</strong></p><p>Enriches the original question with retrieved information.</p><p>The advanced implementation uses RetrievalAugmentationAdvisor to combine these components.</p><p>This is useful because real-world user questions are not always written in the exact words used by the source documents.</p><h3>10. Advisors and Token Usage Monitoring</h3><p>Another important feature of Spring AI is the Advisor API.</p><p>Advisors allow developers to intercept and customize AI interactions.</p><p>They can be used for logging, memory management, request processing, response processing, and other cross-cutting functionality.</p><p>The advisor_app module demonstrates a custom advisor named TokenPrintAdvisor.</p><p>It implements:</p><pre>CallAdvisor<br>StreamAdvisor</pre><p>The advisor can intercept normal model calls and streaming interactions.</p><p>One of its main purposes is to log:</p><ul><li>The submitted prompt.</li><li>The model response.</li><li>Prompt tokens.</li><li>Completion tokens.</li><li>Total tokens consumed.</li></ul><p>For example:</p><pre>logger.info(<br>    &quot;Prompt Token : &quot; +<br>    chatClientResponse.chatResponse()<br>        .getMetadata().getUsage().getPromptTokens()<br>);</pre><p>Token monitoring is important because LLM usage is often metered based on tokens.</p><p>The repository also demonstrates SafeGuardAdvisor, configured with the term games.</p><p>This provides an example of applying request restrictions through an advisor.</p><h3>11. Integrating Different AI Models</h3><p>One of the benefits of Spring AI is that applications can use different model providers without building every integration from scratch.</p><p>The repository explores several providers.</p><h3>OpenAI</h3><p>The project uses OpenAI-compatible ChatClient configurations, including models such as gpt-4o-mini and gpt-4.1 in different modules.</p><h3>Ollama</h3><p>The spring-ai-ollam module demonstrates communicating with a locally hosted Ollama model.</p><p>This is useful for experimenting with local inference rather than relying entirely on cloud-hosted model APIs.</p><h3>Google Gemini</h3><p>The boot-gemini-app module demonstrates Google Gemini integration.</p><p>It exposes a REST endpoint that accepts a query and returns the model’s response.</p><h3>Groq</h3><p>The MCP application uses an OpenAI-compatible configuration pointing to Groq, with the llama-3.1-8b-instant model.</p><p>Together, these examples demonstrate how Spring AI can act as a common integration layer across different model providers.</p><h3>12. Tool Calling with External Services</h3><p>The separate tool-calling-example module demonstrates how language models can interact with external services.</p><p>It includes a weather tool and a date/time tool.</p><p>The ChatService makes the tools available to the model:</p><pre>return chatClient<br>        .prompt()<br>        .tools(new SimpleDateTimeTool(), weatherTool)<br>        .user(q)<br>        .call()<br>        .content();</pre><p>The WeatherTool uses Spring&#39;s RestClient to make an HTTP request to an external weather API.</p><p>The model can determine when weather information is required and request the corresponding tool invocation.</p><p>The date/time tool provides the current time.</p><p>This illustrates an important distinction:</p><p>The model decides which available tool is relevant, while the Java application executes the actual operation.</p><h3>13. Model Context Protocol (MCP)</h3><p>The repository also explores the Model Context Protocol.</p><p>MCP provides a standardized approach for connecting AI applications to external tools and contextual resources.</p><p>The mcp-app module uses Spring AI&#39;s MCP client integration.</p><p>Its ChatClient is configured with a ToolCallbackProvider:</p><pre>this.chatClient = chatClientBuilder<br>        .defaultToolCallbacks(toolCallbackProvider)<br>        .defaultAdvisors(new SimpleLoggerAdvisor())<br>        .build();</pre><p>The MCP client obtains available tool callbacks from the configured MCP servers.</p><p>This makes external tools available to the AI interaction without needing to implement every external capability as a separate Spring AI tool in the application.</p><p>The repository includes a filesystem MCP server configuration using servers.json.</p><p>The configuration must be adapted to the local machine before running because it contains machine-specific filesystem paths.</p><h3>14. Multimodal AI: Image Generation and Audio Transcription</h3><p>Another interesting part of the repository is the spring_ai_media application.</p><p>It explores AI beyond text-based conversations.</p><h3>Image Generation</h3><p>The ImageService uses Spring AI&#39;s ImageModel.</p><p>A user submits a text prompt, and the service requests image generation.</p><p>The implementation configures:</p><ul><li>Model: gpt-image-1</li><li>Image count: 1</li><li>Resolution: 1024 × 1024</li><li>Quality: low</li></ul><p>The generated image is returned as Base64 data and decoded into an image file named image.png.</p><p>The controller exposes:</p><pre>POST /api/images</pre><p>It accepts a prompt as a request parameter.</p><h3>Audio Transcription</h3><p>The AudioService uses TranscriptionModel.</p><p>It converts audio resources into text.</p><p>The implementation also demonstrates configuring transcription options, including language and a contextual prompt.</p><p>The controller exposes:</p><pre>POST /api/v1/audio/text<br>POST /api/v1/audio/transcript<br>POST /api/v1/audio/transcript-with-options</pre><p>These examples demonstrate how Spring AI can integrate image and audio capabilities into a Spring Boot application.</p><h3>15. React Frontend</h3><p>The Help Desk application includes a React frontend.</p><p>The major technologies used are:</p><ul><li>React</li><li>Vite</li><li>React Router</li><li>Axios</li><li>Tailwind CSS</li><li>Lucide React</li><li>UUID</li></ul><p>The frontend provides a chat-based interface.</p><p>The main user journey is:</p><ol><li>The user opens the Help Desk home page.</li><li>The user clicks the button to start a conversation.</li><li>The application navigates to the chat page.</li><li>A unique conversation ID is generated.</li><li>The user writes a message.</li><li>Axios sends the message to the Spring Boot backend.</li><li>The response is displayed in the chat interface.</li></ol><p>The conversation ID is generated using the UUID library:</p><pre>useEffect(() =&gt; {<br>    const id = v444();<br>    setConversationId(id);<br>    inputRef.current.focus();<br>}, []);</pre><p>The frontend sends the message to the backend:</p><pre>export const sendMessagesToServer = async (<br>    message,<br>    conversationId<br>) =&gt; {</pre><pre>    const response = await axios.post(<br>        `${baseURL}/helpdesk`,<br>        message,<br>        {<br>            headers: {<br>                ConversationId: conversationId,<br>            },<br>        }<br>    );</pre><pre>    return response.data;<br>};</pre><p>This allows the backend to associate incoming requests with the correct conversation memory.</p><p>The chat interface also uses React state to display messages, track the loading state, and update the conversation as responses arrive.</p><h3>16. Complete Request Lifecycle</h3><p>Let’s combine the concepts and understand what actually happens when someone reports an issue.</p><p>Suppose a user enters:</p><pre>My laptop is not turning on.</pre><p>The request lifecycle is:</p><p><strong>Step 1: Frontend request</strong></p><p>React sends the message to:</p><pre>POST /api/v1/helpdesk</pre><p>The request includes the ConversationId header.</p><p><strong>Step 2: Controller processing</strong></p><p>The AiController receives the message and forwards it to AIService.</p><p><strong>Step 3: Conversation retrieval</strong></p><p>Spring AI’s MessageChatMemoryAdvisor uses the conversation ID to retrieve the relevant history.</p><p><strong>Step 4: Prompt construction</strong></p><p>The AIService combines the system instructions, user message, conversation context, and available tools.</p><p><strong>Step 5: Model interaction</strong></p><p>The ChatClient communicates with the configured language model.</p><p><strong>Step 6: Tool invocation</strong></p><p>When the assistant determines that a database operation is needed, it can request one of the available Java tools.</p><p>For example, it may request the creation of a ticket after collecting the required details.</p><p><strong>Step 7: Database persistence</strong></p><p>TicketDatabaseTool invokes TicketService.</p><p>TicketService uses TicketRepository to persist the ticket using Spring Data JPA.</p><p><strong>Step 8: Final response</strong></p><p>The model generates its response and the backend returns the content to the React frontend.</p><p><strong>Step 9: UI update</strong></p><p>React appends the assistant’s response to the conversation.</p><p>This demonstrates how traditional backend development and LLM-powered reasoning can work together.</p><h3>17. API Overview</h3><p>Some of the important endpoints in the repository are:</p><p>ModuleEndpointPurposeHelp DeskPOST /api/v1/helpdeskNormal AI conversationHelp DeskPOST /api/v1/helpdesk/streamStreaming AI responseRAGGET /chat?q=...Retrieval-based question answeringAdvanced RAGPOST /chat?q=...Advanced retrievalMemoryGET /chat?q=...Conversation with memoryAdvisorGET /chat?q=...Advisor-based AI interactionOllamaGET /chat?q=...Local model interactionGeminiGET /ai?query=...Gemini interactionMCPPOST /ai/chat?query=...MCP-enabled AI interactionMediaPOST /api/imagesImage generation</p><p>These APIs belong to separate Spring Boot applications, so they should not be assumed to be running inside one single server.</p><h3>18. Technologies Used</h3><p>The project explores a broad range of technologies.</p><p><strong>Backend</strong></p><ul><li>Java</li><li>Spring Boot</li><li>Spring AI</li><li>Spring Web</li><li>Spring Data JPA</li><li>Hibernate</li><li>Maven</li><li>Project Lombok</li><li>Reactor</li></ul><p><strong>Artificial Intelligence</strong></p><ul><li>OpenAI</li><li>Google Gemini</li><li>Groq</li><li>Ollama</li><li>ChatClient</li><li>RAG</li><li>Vector Stores</li><li>Embeddings</li><li>Advisors</li><li>Tool Calling</li><li>MCP</li><li>Image Generation</li><li>Audio Transcription</li></ul><p><strong>Database and Retrieval</strong></p><ul><li>MySQL</li><li>MariaDb</li><li>JDBC</li><li>Vector Search</li></ul><p><strong>Frontend</strong></p><ul><li>React</li><li>Vite</li><li>React Router</li><li>Axios</li><li>Tailwind CSS</li><li>Lucide React</li></ul><h3>19. Current Limitations and Future Improvements</h3><p>Building AI-powered applications also involves understanding what still needs improvement.</p><p>Some potential improvements for this project include:</p><p><strong>1. Improve ticket management</strong></p><p>The current ticket entity has a unique constraint on email. A more flexible design would allow multiple support tickets for the same user while keeping ticket IDs individually unique.</p><p><strong>2. Implement real email delivery</strong></p><p>Integrate an email provider or Spring Mail instead of only printing notification details to the console.</p><p><strong>3. Improve ticket matching</strong></p><p>The current implementation retrieves tickets by email. A more advanced implementation could also compare issue descriptions to identify similar unresolved tickets.</p><p><strong>4. Improve conversation streaming</strong></p><p>The backend already exposes a streaming endpoint, but the current React chat client uses the regular request endpoint. Integrating streaming would allow responses to appear incrementally.</p><p><strong>5. Improve security</strong></p><p>Add authentication, authorization, input validation, rate limiting, and secure API-key management.</p><p><strong>6. Improve configuration management</strong></p><p>Move database credentials, API keys, and environment-specific configuration into environment variables or a secure secrets manager.</p><p><strong>7. Improve observability</strong></p><p>Add structured logging, exception handling, token-cost tracking, and monitoring for model calls and tool execution.</p><p><strong>8. Expand the e-commerce domain</strong></p><p>Although the repository name mentions an e-commerce platform, the current source code does not yet contain a product catalogue, shopping cart, checkout, payment processing, or order management. These would need to be implemented as additional business modules.</p><h3>20. What I Learned</h3><p>Working through these Spring AI examples provides a better understanding of how AI capabilities fit into conventional backend architecture.</p><p>Some of the most important concepts explored are:</p><ul><li>Integrating different LLM providers using Spring AI.</li><li>Using ChatClient to construct model interactions.</li><li>Maintaining conversation history with JDBC-backed memory.</li><li>Customizing interactions using Advisors.</li><li>Monitoring token consumption.</li><li>Building RAG pipelines with vector databases.</li><li>Loading and transforming PDF and JSON documents.</li><li>Giving language models access to Java application tools.</li><li>Connecting external capabilities using MCP.</li><li>Integrating multimodal AI services.</li><li>Connecting a React frontend to an AI-enabled Spring Boot backend.</li></ul><p>The biggest takeaway is that an AI application is not simply a chatbot connected to an API.</p><p>A useful AI-powered application needs a combination of application logic, data management, prompt design, memory, retrieval, external integrations, and reliable backend services.</p><p>Spring AI provides a convenient foundation for bringing these components together in the Java ecosystem.</p><h3>Conclusion</h3><p>This repository represents a practical exploration of the Spring AI ecosystem using Spring Boot.</p><p>Starting with basic ChatClient interactions, it progresses through conversational memory, advisors, RAG, advanced retrieval, tool calling, MCP, and multimodal capabilities.</p><p>The AI Help Desk application brings several of these ideas together in a real application flow, where a user can communicate with an assistant that has access to backend functionality.</p><p>For Java developers interested in building AI-powered applications, understanding these concepts is a useful step towards moving beyond basic LLM API calls and designing applications that can interact with real systems.</p><p><strong>GitHub:</strong> <a href="https://github.com/unknown0149/Spring_ai_Ecommerce_Platform">Spring_ai_Ecommerce_Platform</a></p><p><em>The repository is a continuing exploration of Spring Boot and Spring AI, with room to expand its application features, reliability, and production readiness.</em></p><h3>Acknowledgement</h3><p>Some of the Spring AI example modules follow material and project structure from the <a href="https://github.com/LearnCodeWithDurgesh/spring-ai-yt-series">LearnCodeWithDurgesh Spring AI series</a>. Original tutorial material should be credited where reused, alongside any independently developed extensions and integrations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee1a6cf0e29c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Secret Behind Fast Database Queries: B-Trees, B+ Trees, and Indexing in Spring Boot]]></title>
            <link>https://medium.com/@unknown0149/the-secret-behind-fast-database-queries-b-trees-b-trees-and-indexing-in-spring-boot-bd0106e55ff3?source=rss-6a30a2fdc261------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd0106e55ff3</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[indexing]]></category>
            <dc:creator><![CDATA[Aryan Chauhan]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 12:45:05 GMT</pubDate>
            <atom:updated>2026-11-15T12:45:05.247Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I approached database indexing in a Spring Boot chat application using PostgreSQL, composite indexes, and efficient pagination.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ErEB2CWZOtaT0nuN6BYOw.png" /></figure><p>Imagine a chat application with millions of messages.</p><p>A user opens a conversation and expects the latest 20 messages to appear immediately.</p><p>The application sends a simple SQL query:</p><pre>SELECT *<br>FROM chat_message<br>WHERE conversation_id = 42<br>ORDER BY created_at DESC<br>LIMIT 20;</pre><p>It looks straightforward. But what happens when the database contains millions of messages?</p><p>Does the database inspect every row to find messages belonging to conversation 42, sort them, and then return 20 records?</p><p>It might.</p><p>And this is where <strong>database indexing</strong> becomes important.</p><p>While working on a Spring Boot chat-platform design, I focused on understanding how the database could locate the required records without repeatedly scanning a large table.</p><p>To understand the solution, we first need to understand B-Trees and B+ Trees.</p><h3>1. What is database indexing?</h3><p>Think about finding a particular topic in a 1,000-page textbook.</p><p>You have two options:</p><ul><li>Start from page one and inspect every page.</li><li>Open the index at the back, find the topic, and jump to the relevant page.</li></ul><p>A database index works on a similar principle.</p><p>Without a suitable index, a database may perform a <strong>Sequential Scan</strong>, examining rows one after another.</p><p>With an index, it can use an organized data structure to locate matching records more efficiently.</p><p>For example, consider this table:</p><p>idconversation_idmessagecreated_at10110Hello10:0010242Hi there10:0210315Good morning10:0310442How are you?10:0410510Fine10:05</p><p>An index on conversation_id helps the database locate records belonging to a particular conversation.</p><p>Instead of repeatedly examining every record, the database can navigate through the index.</p><p>The important idea is that an index is a separate data structure maintained by the database. It makes certain reads faster, but it also consumes storage and introduces overhead when records are inserted, updated, or deleted.</p><h3>2. Understanding B-Trees</h3><p>A B-Tree is a self-balancing, multiway search tree.</p><p>The word <em>multiway</em> is important.</p><p>Unlike a Binary Search Tree, where a node has at most two children, a B-Tree node can contain multiple sorted keys and multiple child pointers.</p><p>A simplified structure looks like this:</p><pre>[40 | 80]<br>                 /    |     \<br>                /     |      \<br>       [10 | 20] [45 | 60] [90 | 100]</pre><p>The keys divide the data into ranges.</p><p>For example:</p><ul><li>Values smaller than 40 are in the left subtree.</li><li>Values between 40 and 80 are in the middle subtree.</li><li>Values greater than 80 are in the right subtree.</li></ul><p>A database can navigate through these levels to locate the appropriate key.</p><h3>Why is a B-Tree useful?</h3><p><strong>1. It remains balanced</strong></p><p>All leaf nodes stay at the same depth, so searching does not suddenly become slower because the tree has become a long, unbalanced chain.</p><p><strong>2. Each node stores multiple keys</strong></p><p>Database index nodes are organized into pages. Holding multiple keys per page reduces the number of levels needed to navigate a large index.</p><p><strong>3. It supports different types of searches</strong></p><p>B-Tree indexes are useful for:</p><pre>-- Exact-match search<br>SELECT * FROM users WHERE id = 100;</pre><pre>-- Range search<br>SELECT * FROM products WHERE price BETWEEN 500 AND 2000;</pre><pre>-- Comparison<br>SELECT * FROM employees WHERE salary &gt; 50000;</pre><pre>-- Ordered retrieval<br>SELECT * FROM orders ORDER BY created_at DESC;</pre><p>The search process is approximately logarithmic in the number of indexed entries, although actual database performance also depends on disk access, caching, selectivity, and the query plan.</p><h3>3. What is a B+ Tree, and how is it different?</h3><p>B+ Trees are closely related to B-Trees, but their organization differs.</p><p>The biggest conceptual difference is where the actual record references are stored.</p><p>In the classical B-Tree model, keys and associated record references can appear in internal as well as leaf nodes.</p><p>In a B+ Tree:</p><ul><li>Internal nodes mainly store separator keys and child pointers.</li><li>Leaf nodes store the indexed entries and references to the actual records.</li><li>Leaf nodes are linked, making it efficient to move through consecutive values.</li></ul><p>A simplified B+ Tree:</p><pre>[30 | 60]<br>                   /    |    \<br>                  /     |     \<br>                 /      |      \</pre><pre>       [10 | 20] &lt;-&gt; [30 | 40] &lt;-&gt; [60 | 80]<br>          LEAF          LEAF          LEAF</pre><p>The internal nodes guide the search. Once the database reaches the correct leaf, it can continue through adjacent leaf entries for a range of records.</p><h3>B-Tree vs B+ Tree</h3><p>FeatureClassical B-TreeClassical B+ TreeInternal nodesKeys and record references may appearSeparator keys and child pointersLeaf nodesStore keys and record referencesStore indexed entries and record referencesRecord referencesCan appear at multiple levelsStored at leaf levelRange queriesSupportedParticularly efficient with linked leavesSequential traversalDepends on implementationSupported through linked leaves</p><p><strong>An important real-world distinction:</strong> Database vendors sometimes use the term B-Tree for implementations with leaf-oriented structures. PostgreSQL officially calls its index implementation a B-Tree. IBM Db2 documentation describes its index structure as a B+ Tree.</p><p>So, B-Tree and B+ Tree are useful concepts to understand, but we should not assume every database uses exactly the same textbook implementation.</p><h3>4. Connecting the concept to my Spring Boot project</h3><p>Now let’s move from theory to implementation.</p><p>Consider the chat-platform backend.</p><p>The chat_message table contains messages from different conversations.</p><p>One of the frequently executed queries is:</p><pre>SELECT *<br>FROM chat_message<br>WHERE conversation_id = 42<br>ORDER BY created_at DESC<br>LIMIT 20;</pre><p>The database needs to:</p><ol><li>Find messages belonging to conversation 42.</li><li>Arrange them by creation time, newest first.</li><li>Return only the latest 20 messages.</li></ol><p>Without a suitable index, PostgreSQL may need to scan many rows and perform a separate sort.</p><p>As the table grows, that can become expensive.</p><p>The solution is not to create an index on every column.</p><p>The solution is to understand the query pattern and design an index around it.</p><h3>5. Designing a composite index</h3><p>I chose a composite index containing three columns:</p><pre>CREATE INDEX idx_chat_message_conversation_created_id<br>ON chat_message (<br>    conversation_id,<br>    created_at DESC,<br>    id DESC<br>);</pre><p>Let’s understand why these three columns are present.</p><p><strong>First: </strong><strong>conversation_id</strong></p><p>This is the first condition in the WHERE clause.</p><pre>WHERE conversation_id = 42</pre><p>Putting it first allows the database to navigate to the relevant conversation’s entries efficiently.</p><p><strong>Second: </strong><strong>created_at DESC</strong></p><p>We want the latest messages first.</p><pre>ORDER BY created_at DESC</pre><p>The index stores entries in an order that can support this retrieval.</p><p><strong>Third: </strong><strong>id DESC</strong></p><p>Two messages can have the same timestamp.</p><p>Adding a unique ID as a tie-breaker provides deterministic ordering.</p><p>This matters when implementing pagination. Without a consistent tie-breaker, messages with identical timestamps may appear in an inconsistent order between requests.</p><p>The order of columns matters. PostgreSQL’s multicolumn B-Tree indexes are most effective when queries constrain the leading columns.</p><p>In this case, the index is designed around the exact query:</p><pre>WHERE conversation_id = ?<br>ORDER BY created_at DESC, id DESC<br>LIMIT 20;</pre><p>This is the difference between creating an index randomly and designing one around an application’s actual access pattern.</p><h3>6. Implementing the index in Spring Boot</h3><p>One important clarification:</p><p><strong>Spring Boot does not implement the B-Tree or B+ Tree itself.</strong></p><p>Spring Data JPA sends queries to the database. PostgreSQL creates, maintains, and uses the index internally.</p><p>For this implementation, I use:</p><ul><li>Spring Boot</li><li>Spring Data JPA</li><li>PostgreSQL</li><li>Flyway for database migrations</li></ul><h3>Step 1: Create the database table</h3><p>File:src/main/resources/db/migration/V1__create_chat_message_table.sql</p><pre>CREATE TABLE chat_message (<br>    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,<br>    conversation_id BIGINT NOT NULL,<br>    sender_id BIGINT NOT NULL,<br>    content TEXT NOT NULL,<br>    created_at TIMESTAMPTZ NOT NULL<br>);</pre><p>This gives us a message table with a unique ID, conversation ID, sender ID, content, and timestamp.</p><h3>Step 2: Create the index using Flyway</h3><p>File:src/main/resources/db/migration/V2__add_chat_message_timeline_index.sql</p><pre>CREATE INDEX idx_chat_message_conversation_created_id<br>ON chat_message (<br>    conversation_id,<br>    created_at DESC,<br>    id DESC<br>);</pre><p>When Flyway runs the migrations, PostgreSQL creates the index.</p><p>I prefer versioned migrations over relying on Hibernate to update a production schema automatically. It makes database changes explicit and version-controlled.</p><h3>Step 3: Map the table to a Java entity</h3><p>ChatMessage.java</p><pre>package com.example.chat.message;</pre><pre>import jakarta.persistence.*;<br>import java.time.Instant;</pre><pre>@Entity<br>@Table(name = &quot;chat_message&quot;)<br>public class ChatMessage {</pre><pre>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;</pre><pre>    @Column(name = &quot;conversation_id&quot;, nullable = false)<br>    private Long conversationId;</pre><pre>    @Column(name = &quot;sender_id&quot;, nullable = false)<br>    private Long senderId;</pre><pre>    @Column(nullable = false, columnDefinition = &quot;text&quot;)<br>    private String content;</pre><pre>    @Column(name = &quot;created_at&quot;, nullable = false)<br>    private Instant createdAt;</pre><pre>    protected ChatMessage() {<br>    }</pre><pre>    public Long getId() {<br>        return id;<br>    }</pre><pre>    public Long getConversationId() {<br>        return conversationId;<br>    }</pre><pre>    public Long getSenderId() {<br>        return senderId;<br>    }</pre><pre>    public String getContent() {<br>        return content;<br>    }</pre><pre>    public Instant getCreatedAt() {<br>        return createdAt;<br>    }<br>}</pre><p>Notice that I haven’t added a special B-Tree implementation inside this entity.</p><p>The index already exists in PostgreSQL. The entity simply maps the database table to a Java object.</p><h3>Step 4: Create the Spring Data JPA repository</h3><p>ChatMessageRepository.java</p><pre>package com.example.chat.message;</pre><pre>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.data.jpa.repository.Query;<br>import org.springframework.data.repository.query.Param;</pre><pre>import java.time.Instant;<br>import java.util.List;</pre><pre>public interface ChatMessageRepository<br>        extends JpaRepository&lt;ChatMessage, Long&gt; {</pre><pre>    // First page: retrieve the latest messages.<br>    @Query(value = &quot;&quot;&quot;<br>        SELECT *<br>        FROM chat_message<br>        WHERE conversation_id = :conversationId<br>        ORDER BY created_at DESC, id DESC<br>        LIMIT :limit<br>        &quot;&quot;&quot;, nativeQuery = true)<br>    List&lt;ChatMessage&gt; findLatestMessages(<br>            @Param(&quot;conversationId&quot;) Long conversationId,<br>            @Param(&quot;limit&quot;) int limit<br>    );</pre><pre>    // Next page: retrieve messages older than the cursor.<br>    @Query(value = &quot;&quot;&quot;<br>        SELECT *<br>        FROM chat_message<br>        WHERE conversation_id = :conversationId<br>          AND (created_at, id) &lt; (:beforeCreatedAt, :beforeId)<br>        ORDER BY created_at DESC, id DESC<br>        LIMIT :limit<br>        &quot;&quot;&quot;, nativeQuery = true)<br>    List&lt;ChatMessage&gt; findOlderMessages(<br>            @Param(&quot;conversationId&quot;) Long conversationId,<br>            @Param(&quot;beforeCreatedAt&quot;) Instant beforeCreatedAt,<br>            @Param(&quot;beforeId&quot;) Long beforeId,<br>            @Param(&quot;limit&quot;) int limit<br>    );<br>}</pre><p>Here I used Spring Data JPA’s @Query with nativeQuery = true.</p><p>Why native SQL?</p><p>Because the query uses PostgreSQL’s row-value comparison:</p><pre>(created_at, id) &lt; (:beforeCreatedAt, :beforeId)</pre><p>This allows us to use the last message from the previous response as a cursor.</p><h3>Step 5: Add the service layer</h3><p>ChatMessageService.java</p><pre>package com.example.chat.message;</pre><pre>import org.springframework.http.HttpStatus;<br>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Transactional;<br>import org.springframework.web.server.ResponseStatusException;</pre><pre>import java.time.Instant;<br>import java.util.List;</pre><pre>@Service<br>public class ChatMessageService {</pre><pre>    private final ChatMessageRepository repository;</pre><pre>    public ChatMessageService(ChatMessageRepository repository) {<br>        this.repository = repository;<br>    }</pre><pre>    @Transactional(readOnly = true)<br>    public List&lt;MessageResponse&gt; getMessages(<br>            Long conversationId,<br>            Instant beforeCreatedAt,<br>            Long beforeId,<br>            int limit<br>    ) {</pre><pre>        if (limit &lt; 1 || limit &gt; 100) {<br>            throw new ResponseStatusException(<br>                    HttpStatus.BAD_REQUEST,<br>                    &quot;Limit must be between 1 and 100&quot;<br>            );<br>        }</pre><pre>        // Both cursor values must be provided together.<br>        if ((beforeCreatedAt == null) != (beforeId == null)) {<br>            throw new ResponseStatusException(<br>                    HttpStatus.BAD_REQUEST,<br>                    &quot;Both cursor fields are required&quot;<br>            );<br>        }</pre><pre>        List&lt;ChatMessage&gt; messages;</pre><pre>        if (beforeCreatedAt == null) {<br>            messages = repository.findLatestMessages(<br>                    conversationId,<br>                    limit<br>            );<br>        } else {<br>            messages = repository.findOlderMessages(<br>                    conversationId,<br>                    beforeCreatedAt,<br>                    beforeId,<br>                    limit<br>            );<br>        }</pre><pre>        return messages.stream()<br>                .map(MessageResponse::from)<br>                .toList();<br>    }<br>}</pre><p>I also used a DTO rather than exposing the JPA entity directly.</p><p>MessageResponse.java</p><pre>package com.example.chat.message;</pre><pre>import java.time.Instant;</pre><pre>public record MessageResponse(<br>        Long id,<br>        Long conversationId,<br>        Long senderId,<br>        String content,<br>        Instant createdAt<br>) {<br>    public static MessageResponse from(ChatMessage message) {<br>        return new MessageResponse(<br>                message.getId(),<br>                message.getConversationId(),<br>                message.getSenderId(),<br>                message.getContent(),<br>                message.getCreatedAt()<br>        );<br>    }<br>}</pre><h3>Step 6: Expose the API through a controller</h3><p>ChatMessageController.java</p><pre>package com.example.chat.message;</pre><pre>import org.springframework.format.annotation.DateTimeFormat;<br>import org.springframework.web.bind.annotation.*;</pre><pre>import java.time.Instant;<br>import java.util.List;</pre><pre>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class ChatMessageController {</pre><pre>    private final ChatMessageService service;</pre><pre>    public ChatMessageController(ChatMessageService service) {<br>        this.service = service;<br>    }</pre><pre>    @GetMapping(&quot;/conversations/{conversationId}/messages&quot;)<br>    public List&lt;MessageResponse&gt; getMessages(<br>            @PathVariable Long conversationId,</pre><pre>            @RequestParam(defaultValue = &quot;20&quot;)<br>            int limit,</pre><pre>            @RequestParam(required = false)<br>            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)<br>            Instant beforeCreatedAt,</pre><pre>            @RequestParam(required = false)<br>            Long beforeId<br>    ) {<br>        return service.getMessages(<br>                conversationId,<br>                beforeCreatedAt,<br>                beforeId,<br>                limit<br>        );<br>    }<br>}</pre><p>In a real chat application, the controller or service must also verify that the authenticated user is authorized to access the requested conversation. An index improves query access; it does not provide authorization.</p><h3>7. Why did I use cursor-based pagination?</h3><p>There is another important database concept in this implementation.</p><p>Traditional pagination often looks like this:</p><pre>SELECT *<br>FROM chat_message<br>WHERE conversation_id = 42<br>ORDER BY created_at DESC, id DESC<br>LIMIT 20 OFFSET 10000;</pre><p>The problem is that as the offset grows, the database may need to walk through and discard an increasing number of matching entries before returning the requested page.</p><p>Instead, I used cursor-based pagination.</p><p>For the first request:</p><pre>GET /api/conversations/42/messages?limit=20</pre><p>Suppose the last returned message has:</p><pre>{<br>  &quot;id&quot;: 881,<br>  &quot;createdAt&quot;: &quot;2026-11-15T11:30:00Z&quot;<br>}</pre><p>The next request becomes:</p><pre>GET /api/conversations/42/messages?limit=20&amp;beforeCreatedAt=2026-11-15T11:30:00Z&amp;beforeId=881</pre><p>PostgreSQL now retrieves messages older than that cursor.</p><p>The composite index supports this access pattern because it contains the conversation ID, timestamp, and unique tie-breaker.</p><p>This approach avoids repeatedly skipping a large OFFSET and gives more predictable pagination as new messages arrive.</p><h3>8. How do I verify that PostgreSQL is actually using my index?</h3><p>Creating an index does not guarantee that PostgreSQL will use it.</p><p>The query planner chooses a plan based on table statistics, estimated costs, and the query itself.</p><p>This is why I use:</p><pre>EXPLAIN (ANALYZE, BUFFERS)<br>SELECT *<br>FROM chat_message<br>WHERE conversation_id = 42<br>ORDER BY created_at DESC, id DESC<br>LIMIT 20;</pre><p>Run this before and after creating the index, using the same representative dataset.</p><p>Look for a plan containing something similar to:</p><pre>Limit<br>  -&gt; Index Scan using<br>     idx_chat_message_conversation_created_id</pre><p>Important things to examine:</p><ul><li><strong>Index Scan:</strong> Is PostgreSQL navigating through the index?</li><li><strong>Index Cond:</strong> Which conditions are being applied through the index?</li><li><strong>Sort:</strong> Is an additional sorting operation required?</li><li><strong>Actual Time:</strong> How long did the execution nodes take?</li><li><strong>Buffers:</strong> How many database pages were hit or read?</li></ul><p>You may still see a Sequential Scan on a small table. That is not necessarily an error. If PostgreSQL estimates that scanning the table is cheaper, it can legitimately choose that plan.</p><p>The important thing is to test with realistic data rather than assuming that creating an index automatically improves performance.</p><h3>9. Are indexes always beneficial?</h3><p>No. This is one of the biggest mistakes developers make when learning database indexing.</p><p>An index has costs:</p><p><strong>Storage:</strong> Every index takes additional disk space.</p><p><strong>Insert overhead:</strong> When a new message is inserted, PostgreSQL also needs to maintain the relevant index.</p><p><strong>Update overhead:</strong> Changes to indexed columns can require index maintenance.</p><p><strong>Maintenance:</strong> Indexes need to be monitored and managed as the database grows.</p><p>That is why I would not create separate indexes on every column just because those columns appear in queries.</p><p>I would first identify the frequently executed queries, understand their WHERE and ORDER BY conditions, and then choose an index that supports the actual access pattern.</p><h3>10. What I learned from this implementation</h3><p>The most important lesson for me was that database performance is not only about writing a correct SQL query.</p><p>It is also about understanding how the database retrieves the data.</p><p>Here are the key takeaways:</p><ol><li>B-Trees and B+ Trees explain how databases organize searchable index entries.</li><li>Composite indexes should be designed around actual query patterns.</li><li>Column order matters, especially the leading columns of a B-Tree index.</li><li>Indexes can support both filtering and ordered retrieval.</li><li>Cursor-based pagination is useful for large, continuously growing datasets.</li><li>EXPLAIN ANALYZE is essential for verifying the query plan instead of guessing.</li><li>Every index has a write and storage cost, so indexing should be intentional.</li></ol><p><strong>The biggest takeaway: Don’t just optimize your SQL query. Understand how your database executes it.</strong></p><p>That is when DBMS concepts start becoming genuinely useful in backend development.</p><h3>Official documentation and further reading</h3><p>These are the references I used to cross-check the database and Spring implementation:</p><ol><li><a href="https://www.postgresql.org/docs/current/indexes.html">PostgreSQL — Introduction to Indexes</a></li><li><a href="https://www.postgresql.org/docs/current/btree.html">PostgreSQL — B-Tree Indexes</a></li><li><a href="https://www.postgresql.org/docs/current/indexes-multicolumn.html">PostgreSQL — Multicolumn Indexes</a></li><li><a href="https://www.postgresql.org/docs/current/indexes-ordering.html">PostgreSQL — Indexes and ORDER BY</a></li><li><a href="https://www.postgresql.org/docs/current/using-explain.html">PostgreSQL — Using EXPLAIN</a></li><li><a href="https://docs.spring.io/spring-boot/how-to/data-initialization.html">Spring Boot — Database Initialization and Flyway</a></li><li><a href="https://docs.spring.io/spring-data/jpa/reference/jpa/query-methods.html">Spring Data JPA — Query Methods and Native Queries</a></li><li><a href="https://www.ibm.com/docs/en/db2/11.5.x?topic=indexes-index-structure">IBM Db2 — B+ Tree Index Structure</a></li></ol><p>#DatabaseManagement #DBMS #DatabaseIndexing #BTree #BPlusTree #SpringBoot #PostgreSQL #BackendDevelopment #Java</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd0106e55ff3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Validation Groups Explained: Why Do We Need Empty Interfaces?]]></title>
            <link>https://medium.com/@unknown0149/spring-boot-validation-groups-explained-why-do-we-need-empty-interfaces-30cf379ad1e2?source=rss-6a30a2fdc261------2</link>
            <guid isPermaLink="false">https://medium.com/p/30cf379ad1e2</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[validator]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Aryan Chauhan]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 10:45:18 GMT</pubDate>
            <atom:updated>2026-11-03T10:49:41.080Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding Jakarta Bean Validation, Marker Interfaces, and how to apply different validation rules for Create and Update REST APIs.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbrW_cUsC4x1eFzD-RcdQw.png" /></figure><h3>Introduction</h3><p>While building a Patient Management REST API using Java and Spring Boot, I came across something interesting.</p><p>I was creating a new interface called:</p><pre>public interface CreatePatientValidationGroup {</pre><pre>}</pre><p>At first, this looked a little strange.</p><p>An interface with no methods, no variables, and absolutely nothing inside it.</p><p>Naturally, a question came to mind:</p><p><strong>Why would we create an interface if we aren’t going to put anything inside it?</strong></p><p>After understanding the concept, I realized that this small interface solves a useful problem when building REST APIs: applying different validation rules depending on what operation we are performing.</p><p>This concept is called <strong>Validation Groups</strong> in Jakarta Bean Validation.</p><p>Before understanding Validation Groups, let’s understand what validation actually does in Spring Boot.</p><h3>1. What Is Validation in Spring Boot?</h3><p>Imagine we are building a Patient Management REST API.</p><p>Our API allows users to:</p><ul><li>Register a new patient.</li><li>Update an existing patient’s information.</li><li>Retrieve patient details.</li><li>Delete a patient.</li></ul><p>When someone sends a request to our API, we cannot blindly trust the incoming data.</p><p>For example, someone might send:</p><pre>{<br>    &quot;name&quot;: &quot;&quot;,<br>    &quot;email&quot;: &quot;this-is-not-an-email&quot;,<br>    &quot;dateOfBirth&quot;: null<br>}</pre><p>This request contains several problems:</p><ol><li>The patient’s name is empty.</li><li>The email address is invalid.</li><li>The date of birth is missing.</li></ol><p>We should catch these problems before sending the data to our service layer or saving anything to the database.</p><p>This is where validation comes into the picture.</p><p><strong>Validation is the process of checking whether incoming data satisfies the rules defined by our application.</strong></p><p>Spring Boot supports Jakarta Bean Validation, which allows us to define validation rules using annotations directly on Java classes.</p><p>Some commonly used validation annotations are:</p><p>AnnotationPurpose@NotNullValue cannot be null.@NotEmptyValue cannot be null or empty.@NotBlankString cannot be null, empty or whitespace only.@EmailString must have a valid email format.@SizeChecks the minimum and maximum size.@MinNumber must be greater than or equal to a minimum.@MaxNumber must be less than or equal to a maximum.@PastDate must be in the past.@FutureDate must be in the future.@PatternString must match a specified regular expression.</p><p>Let’s understand how we use them.</p><h3>1.1 Creating our first DTO with validation</h3><p>In a REST API, we generally use DTOs (Data Transfer Objects) to receive data from the client.</p><p>For our patient service, let’s create a PatientRequestDTO.</p><pre>import jakarta.validation.constraints.*;</pre><pre>import java.time.LocalDate;</pre><pre>public class PatientRequestDTO {</pre><pre>    @NotBlank(message = &quot;Name is required&quot;)<br>    private String name;</pre><pre>    @NotBlank(message = &quot;Email is required&quot;)<br>    @Email(message = &quot;Please provide a valid email&quot;)<br>    private String email;</pre><pre>    @NotNull(message = &quot;Date of birth is required&quot;)<br>    @Past(message = &quot;Date of birth must be in the past&quot;)<br>    private LocalDate dateOfBirth;</pre><pre>    // Getters and setters<br>}</pre><p>Let’s understand each annotation.</p><h3>@NotNull</h3><pre>@NotNull<br>private String name;</pre><p>This ensures that the value is not null.</p><p>However, there is an important difference between @NotNull and @NotBlank.</p><p>Consider these values:</p><pre>name = null;<br>name = &quot;&quot;;<br>name = &quot;   &quot;;<br>name = &quot;Aryan&quot;;</pre><p>@NotNull only rejects the first value.</p><p>It allows an empty string and a string containing spaces because both are non-null.</p><h3>@NotBlank</h3><pre>@NotBlank<br>private String name;</pre><p>This annotation is specifically useful for strings.</p><p>It rejects:</p><ul><li>null</li><li>&quot;&quot;</li><li>&quot; &quot;</li></ul><p>It accepts:</p><pre>name = &quot;Aryan&quot;;</pre><p>This is generally more suitable for names, addresses and other mandatory text fields.</p><h3>@Email</h3><pre>@Email<br>private String email;</pre><p>This validates the email format.</p><p>For example:</p><pre>aryan@gmail.com       Valid<br>aryan123@yahoo.com    Valid<br>invalid-email         Invalid</pre><p>An important detail: @Email does not make a field mandatory. It considers null valid.</p><p>Therefore, when email is mandatory, we combine:</p><pre>@NotBlank<br>@Email<br>private String email;</pre><p>The first annotation checks whether a value was provided.</p><p>The second checks whether the provided value has a valid email format.</p><h3>@Past</h3><pre>@Past<br>private LocalDate dateOfBirth;</pre><p>This ensures that the supplied date is earlier than the current date.</p><p>For example:</p><pre>2003-05-10    Valid<br>1998-10-15    Valid<br>2030-01-01    Invalid</pre><p>Unlike @NotNull, @Past allows null values. That is why we combine it with @NotNull when the date is mandatory.</p><h3>2. How Does Spring Actually Trigger Validation?</h3><p>Writing validation annotations inside a DTO is not enough.</p><p>We also need to tell Spring to execute those validation rules when processing an incoming request.</p><p>Let’s look at our controller.</p><pre>@PostMapping(&quot;/patients&quot;)<br>public ResponseEntity&lt;PatientResponseDTO&gt; createPatient(<br>        @RequestBody<br>        @Valid PatientRequestDTO patientDTO) {</pre><pre>    return ResponseEntity.ok(<br>        patientService.savePatient(patientDTO)<br>    );<br>}</pre><p>There are three important things here.</p><h3>@RequestBody</h3><pre>@RequestBody</pre><p>This tells Spring that the incoming HTTP request body should be converted into a Java object.</p><p>For example, a client sends:</p><pre>{<br>    &quot;name&quot;: &quot;Aryan&quot;,<br>    &quot;email&quot;: &quot;aryan@gmail.com&quot;,<br>    &quot;dateOfBirth&quot;: &quot;2003-05-10&quot;<br>}</pre><p>Spring uses an HTTP message converter, typically Jackson, to convert this JSON into a PatientRequestDTO object.</p><h3>@Valid</h3><pre>@Valid PatientRequestDTO patientDTO</pre><p>This tells Spring to execute the Bean Validation constraints on the received object.</p><p>The flow looks like this:</p><ol><li>Client sends a JSON request.</li><li>Spring converts JSON into a DTO.</li><li>Spring executes the validation annotations.</li><li>If validation succeeds, the controller method executes.</li><li>The controller calls the service layer.</li><li>The service processes the request.</li></ol><p>But what happens when validation fails?</p><p>Spring raises a MethodArgumentNotValidException for the usual individual @RequestBody validation path.</p><p>This exception can be handled by a global exception handler, and the API can return HTTP 400 Bad Request.</p><p>We will implement this later.</p><p>For now, remember:</p><p><strong>@Valid tells Spring to validate the object using the Default validation group.</strong></p><p>And that brings us to the actual problem.</p><h3>3. The Problem: Different Operations Can Have Different Validation Requirements</h3><p>Let’s imagine our application has two operations.</p><p><strong>Operation 1: Create a Patient</strong></p><p>When registering a new patient, we want all the required information:</p><pre>{<br>    &quot;name&quot;: &quot;Aryan&quot;,<br>    &quot;email&quot;: &quot;aryan@gmail.com&quot;,<br>    &quot;dateOfBirth&quot;: &quot;2003-05-10&quot;<br>}</pre><p>All three fields are mandatory.</p><p>That makes sense because we are creating a completely new patient record.</p><p><strong>Operation 2: Update a Patient</strong></p><p>Now imagine we want to update an existing patient’s information.</p><p>Suppose our update operation allows the client to change the patient’s name while leaving the email and date of birth unchanged.</p><p>The request might look like:</p><pre>{<br>    &quot;name&quot;: &quot;Aryan Chauhan&quot;<br>}</pre><p>But remember our DTO:</p><pre>public class PatientRequestDTO {</pre><pre>    @NotBlank<br>    private String name;</pre><pre>    @NotBlank<br>    @Email<br>    private String email;</pre><pre>    @NotNull<br>    private LocalDate dateOfBirth;<br>}</pre><p>There is a problem here.</p><p>Spring will execute all the default validation constraints.</p><p>Even though we only want to update the name, validation will reject the request because email and dateOfBirth are missing.</p><p>Why?</p><p>Because our DTO says that all three fields are mandatory.</p><p>But our update operation does not require all three fields.</p><p>We now have a situation where:</p><ul><li>Creating a patient requires all three fields.</li><li>Updating a patient may require only some of those fields.</li></ul><p><strong>The same DTO is being used for two different operations, but both operations don’t have the same validation requirements.</strong></p><p>We could create two separate DTOs.</p><p>For example:</p><pre>CreatePatientRequestDTO<br>UpdatePatientRequestDTO</pre><p>That is a perfectly valid design.</p><p>However, what if we want to reuse the same DTO while applying different validation rules depending on the operation?</p><p>This is where Validation Groups become useful.</p><h3>4. What Are Validation Groups?</h3><p>Validation Groups allow us to organize constraints into different groups and execute only the group required for a particular operation.</p><p>In simple words:</p><p><strong>Instead of validating every constraint every time, we can tell Spring which set of validation rules should execute.</strong></p><p>For example:</p><p>OperationValidation rulesCreate PatientName, email and date of birth are mandatory.Update PatientName is mandatory; email and date of birth are optional.</p><p>We can create separate validation groups for these operations.</p><pre>CreatePatientValidationGroup<br>UpdatePatientValidationGroup</pre><p>But here comes the interesting part.</p><p>Both of these can be empty interfaces.</p><p>Why?</p><p>Because they are not responsible for implementing any logic.</p><p>They simply identify a collection of validation constraints.</p><h3>5. What Is a Marker Interface?</h3><p>Before continuing, let’s understand the Java concept behind these interfaces.</p><p>A marker interface is an interface that does not contain any methods or fields.</p><p>Its purpose is to mark or identify a class or a particular category of behavior.</p><p>For example, Java has a well-known marker interface:</p><pre>import java.io.Serializable;</pre><pre>public class Patient implements Serializable {</pre><pre>}</pre><p>Serializable does not require us to implement any methods.</p><p>It identifies that the object supports Java serialization.</p><p>Similarly, in validation groups, an empty interface acts as an identifier for a particular set of validation constraints.</p><p>Let’s create our first interface.</p><p><strong>CreatePatientValidationGroup.java</strong></p><pre>package com.pm.patientservice.dto.validators;</pre><pre>public interface CreatePatientValidationGroup {</pre><pre>}</pre><p>Now create another one.</p><p><strong>UpdatePatientValidationGroup.java</strong></p><pre>package com.pm.patientservice.dto.validators;</pre><pre>public interface UpdatePatientValidationGroup {</pre><pre>}</pre><p>Notice that both interfaces are empty.</p><p>We do not need to write any methods inside them.</p><p>They simply provide a type that we can associate with our validation annotations.</p><p>Think of them as labels:</p><ul><li>CreatePatientValidationGroup identifies validation rules for creating a patient.</li><li>UpdatePatientValidationGroup identifies validation rules for updating a patient.</li></ul><p>Now let’s see how we actually use them.</p><h3>6. How Do We Assign Validation Rules to Groups?</h3><p>Remember our validation annotations?</p><p>For example:</p><pre>@NotBlank<br>private String name;</pre><p>Every Bean Validation constraint annotation has an attribute called groups.</p><p>Its purpose is to specify which validation group or groups the constraint belongs to.</p><p>For example:</p><pre>@NotBlank(groups = CreatePatientValidationGroup.class)<br>private String name;</pre><p>Let’s break this down.</p><h3>What is groups?</h3><pre>groups =</pre><p>This is an attribute provided by Bean Validation constraint annotations.</p><p>It accepts one or more group classes.</p><h3>What is CreatePatientValidationGroup.class?</h3><pre>CreatePatientValidationGroup.class</pre><p>This refers to the Class object representing our marker interface.</p><p>We are telling the validation provider:</p><p>“Execute this particular validation rule when the CreatePatientValidationGroup is selected.”</p><p>Notice that we use .class, not an object of the interface.</p><p>We are passing the type itself because the validation framework identifies groups using Java class types.</p><h3>Can one constraint belong to multiple groups?</h3><p>Absolutely.</p><p>For example:</p><pre>@NotBlank(groups = {<br>    CreatePatientValidationGroup.class,<br>    UpdatePatientValidationGroup.class<br>})<br>private String name;</pre><p>This means that the name must not be blank during both create and update operations.</p><p>A constraint can belong to more than one validation group.</p><p>That makes the system flexible.</p><h3>7. Implementing Validation Groups in Our Patient DTO</h3><p>Now let’s implement the complete example.</p><p>We want these rules:</p><p><strong>During Create:</strong></p><ul><li>Name is mandatory.</li><li>Email is mandatory.</li><li>Email must have a valid format.</li><li>Date of birth is mandatory.</li><li>Date of birth must be in the past.</li></ul><p><strong>During Update:</strong></p><ul><li>Name is mandatory.</li><li>Email is optional, but if supplied, it must be valid.</li><li>Date of birth is optional, but if supplied, it must be in the past.</li></ul><p>Let’s modify our DTO.</p><pre>package com.pm.patientservice.dto;</pre><pre>import com.pm.patientservice.dto.validators.CreatePatientValidationGroup;<br>import com.pm.patientservice.dto.validators.UpdatePatientValidationGroup;</pre><pre>import jakarta.validation.constraints.Email;<br>import jakarta.validation.constraints.NotBlank;<br>import jakarta.validation.constraints.NotNull;<br>import jakarta.validation.constraints.Past;</pre><pre>import java.time.LocalDate;</pre><pre>public class PatientRequestDTO {</pre><pre>    @NotBlank(message = &quot;Name is required&quot;)<br>    private String name;</pre><pre>    @NotBlank(<br>        message = &quot;Email is required&quot;,<br>        groups = CreatePatientValidationGroup.class<br>    )<br>    @Email(<br>        message = &quot;Please provide a valid email&quot;,<br>        groups = {<br>            CreatePatientValidationGroup.class,<br>            UpdatePatientValidationGroup.class<br>        }<br>    )<br>    private String email;</pre><pre>    @NotNull(<br>        message = &quot;Date of birth is required&quot;,<br>        groups = CreatePatientValidationGroup.class<br>    )<br>    @Past(<br>        message = &quot;Date of birth must be in the past&quot;,<br>        groups = {<br>            CreatePatientValidationGroup.class,<br>            UpdatePatientValidationGroup.class<br>        }<br>    )<br>    private LocalDate dateOfBirth;</pre><pre>    // Getters and setters<br>}</pre><p>Let’s understand every field carefully.</p><h3>Name field</h3><pre>@NotBlank(message = &quot;Name is required&quot;)<br>private String name;</pre><p>We haven’t specified any groups attribute.</p><p>This means the constraint belongs to the Default validation group.</p><p>We will see shortly how to include this constraint in our custom groups.</p><h3>Email field</h3><pre>@NotBlank(groups = CreatePatientValidationGroup.class)</pre><p>This means email cannot be blank during patient creation.</p><p>We haven’t assigned NotBlank to the update group.</p><p>Therefore, the update operation can omit the email.</p><p>Next:</p><pre>@Email(groups = {<br>    CreatePatientValidationGroup.class,<br>    UpdatePatientValidationGroup.class<br>})</pre><p>This checks the email format during both operations.</p><p>Remember that @Email accepts null.</p><p>Therefore:</p><ul><li>During creation, @NotBlank makes email mandatory.</li><li>During updating, email may be omitted.</li><li>If an email is supplied, @Email checks its format.</li></ul><h3>Date of birth field</h3><pre>@NotNull(groups = CreatePatientValidationGroup.class)</pre><p>This makes date of birth mandatory during creation.</p><p>Next:</p><pre>@Past(groups = {<br>    CreatePatientValidationGroup.class,<br>    UpdatePatientValidationGroup.class<br>})</pre><p>This checks the date during both operations.</p><p>Since @Past accepts null, the update operation can omit date of birth.</p><p>Now we have successfully assigned different validation rules to different operations.</p><p>But there is one important problem we still need to understand.</p><h3>8. Understanding the Default Validation Group</h3><p>This is one of the most important things to understand when working with Validation Groups.</p><p>Consider this annotation:</p><pre>@NotBlank<br>private String name;</pre><p>We did not specify a group.</p><p>So which group does this constraint belong to?</p><p>The answer is:</p><p><strong>Default.class</strong></p><p>Jakarta Bean Validation automatically assigns every constraint to the Default group when no group is explicitly specified.</p><p>You can also write it explicitly:</p><pre>@NotBlank(groups = Default.class)<br>private String name;</pre><p>Both are equivalent.</p><p>Now imagine we trigger validation like this:</p><pre>@Validated(CreatePatientValidationGroup.class)</pre><p>Which constraints will execute?</p><p>The constraints assigned to CreatePatientValidationGroup.</p><p>But what about constraints assigned to Default?</p><p>They will not automatically execute just because we selected a custom group.</p><p>That means our name validation could be skipped!</p><p>This is an important detail.</p><p>There are two common ways to solve this.</p><h3>Approach 1: Assign common constraints to every required group</h3><p>We can write:</p><pre>@NotBlank(groups = {<br>    CreatePatientValidationGroup.class,<br>    UpdatePatientValidationGroup.class<br>})<br>private String name;</pre><p>Now name validation explicitly belongs to both groups.</p><p>This approach works perfectly.</p><h3>Approach 2: Make custom groups extend Default</h3><p>We can also modify our interfaces.</p><p><strong>CreatePatientValidationGroup.java</strong></p><pre>import jakarta.validation.groups.Default;</pre><pre>public interface CreatePatientValidationGroup extends Default {<br>}</pre><p><strong>UpdatePatientValidationGroup.java</strong></p><pre>import jakarta.validation.groups.Default;</pre><pre>public interface UpdatePatientValidationGroup extends Default {<br>}</pre><p>What does this mean?</p><p>In Java, an interface can extend another interface.</p><p>Since both custom groups extend Default, validating either custom group also includes the constraints belonging to the Default group.</p><p>Conceptually:</p><pre>CreatePatientValidationGroup<br>            |<br>            v<br>         Default</pre><p>And:</p><pre>UpdatePatientValidationGroup<br>            |<br>            v<br>         Default</pre><p>Now, when we select either custom group, the Default constraints are included.</p><p>This allows us to keep common validation constraints simple:</p><pre>@NotBlank<br>private String name;</pre><p>We don’t need to explicitly assign the name constraint to both groups.</p><p><strong>For our example, we can use Approach 2.</strong></p><p>It keeps the DTO cleaner when common validation rules should apply to every operation.</p><h3>9. How Do We Trigger a Custom Validation Group?</h3><p>So far, we have:</p><ol><li>Created marker interfaces.</li><li>Assigned validation constraints to groups.</li><li>Understood how the Default group works.</li></ol><p>But defining the groups is not enough.</p><p>We must tell Spring which group to execute when an API is called.</p><p>This is where @Validated comes in.</p><p>@Validated is a Spring annotation that supports specifying validation groups.</p><p>Its package is:</p><pre>import org.springframework.validation.annotation.Validated;</pre><p>Let’s modify our controller.</p><h3>9.1 Create Patient API</h3><pre>@PostMapping(&quot;/patients&quot;)<br>public ResponseEntity&lt;PatientResponseDTO&gt; createPatient(</pre><pre>        @RequestBody<br>        @Validated(CreatePatientValidationGroup.class)<br>        PatientRequestDTO patientDTO<br>) {</pre><pre>    return ResponseEntity.ok(<br>        patientService.savePatient(patientDTO)<br>    );<br>}</pre><p>Look at this part:</p><pre>@Validated(CreatePatientValidationGroup.class)</pre><p>We are telling Spring to validate this request using the CreatePatientValidationGroup.</p><p>Therefore, Spring executes:</p><ul><li>Constraints belonging to CreatePatientValidationGroup.</li><li>Constraints belonging to its parent groups, including Default, because our group extends Default.</li></ul><p>It does not execute unrelated custom groups.</p><h3>9.2 Update Patient API</h3><p>Now let’s create the update endpoint.</p><pre>@PatchMapping(&quot;/patients/{id}&quot;)<br>public ResponseEntity&lt;PatientResponseDTO&gt; updatePatient(</pre><pre>        @PathVariable UUID id,</pre><pre>        @RequestBody<br>        @Validated(UpdatePatientValidationGroup.class)<br>        PatientRequestDTO patientDTO<br>) {</pre><pre>    return ResponseEntity.ok(<br>        patientService.updatePatient(id, patientDTO)<br>    );<br>}</pre><p>Notice the difference:</p><p>For creation:</p><pre>@Validated(CreatePatientValidationGroup.class)</pre><p>For updating:</p><pre>@Validated(UpdatePatientValidationGroup.class)</pre><p>The same DTO is used in both operations, but different validation groups are activated.</p><p>This is the main advantage of Validation Groups.</p><p><strong>One DTO, multiple sets of validation rules.</strong></p><p>An important API-design detail: our example requires the name even during PATCH. That is a deliberate rule in this example, not a requirement of PATCH itself. In an API where every field is optional during PATCH, use an appropriate update DTO or optional-field validation strategy instead.</p><h3>10. How Does the Complete Request Flow Work?</h3><p>Now let’s connect everything.</p><p>Imagine the client sends a request to:</p><pre>POST /patients</pre><p>The request body is:</p><pre>{<br>    &quot;name&quot;: &quot;Aryan&quot;,<br>    &quot;email&quot;: &quot;aryan@gmail.com&quot;,<br>    &quot;dateOfBirth&quot;: &quot;2003-05-10&quot;<br>}</pre><p>The flow is:</p><p><strong>Step 1: Request received</strong></p><p>Spring MVC receives the HTTP request.</p><p><strong>Step 2: JSON converted into DTO</strong></p><p>Jackson converts the JSON into a PatientRequestDTO object.</p><p><strong>Step 3: Validation group selected</strong></p><p>Spring sees:</p><pre>@Validated(CreatePatientValidationGroup.class)</pre><p>It selects the create validation group.</p><p><strong>Step 4: Constraints executed</strong></p><p>The validation provider checks:</p><pre>Name       -&gt; NotBlank<br>Email      -&gt; NotBlank + Email<br>Date       -&gt; NotNull + Past</pre><p>Common constraints from Default are also included because our custom group extends Default.</p><p><strong>Step 5: Validation result</strong></p><p>There are two possible outcomes.</p><p>If validation succeeds, the controller method executes and calls the service.</p><p>If validation fails, Spring raises a validation exception and the service method is not executed.</p><p>For an invalid request, we can return HTTP 400 Bad Request.</p><p>The same flow happens for updates, except that the update validation group is selected.</p><h3>11. Handling Validation Errors Using GlobalExceptionHandler</h3><p>We should not leave validation errors without a proper response.</p><p>In our application, we can use @ControllerAdvice to handle exceptions globally.</p><p>Let’s understand the implementation.</p><pre>package com.pm.patientservice.exception;</pre><pre>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.MethodArgumentNotValidException;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.ControllerAdvice;</pre><pre>import java.util.HashMap;<br>import java.util.Map;</pre><pre>@ControllerAdvice<br>public class GlobalExceptionHandler {</pre><pre>    @ExceptionHandler(MethodArgumentNotValidException.class)<br>    public ResponseEntity&lt;Map&lt;String, String&gt;&gt; handleValidationException(<br>            MethodArgumentNotValidException ex) {</pre><pre>        Map&lt;String, String&gt; errors = new HashMap&lt;&gt;();</pre><pre>        ex.getBindingResult().getFieldErrors().forEach(error -&gt; {</pre><pre>            errors.put(<br>                error.getField(),<br>                error.getDefaultMessage()<br>            );</pre><pre>        });</pre><pre>        return ResponseEntity.badRequest().body(errors);<br>    }<br>}</pre><p>Let’s understand each part.</p><h3>@ControllerAdvice</h3><pre>@ControllerAdvice</pre><p>This tells Spring that the class can handle exceptions across multiple controllers.</p><p>Instead of writing exception-handling logic in every controller, we can centralize it in one place.</p><h3>@ExceptionHandler</h3><pre>@ExceptionHandler(MethodArgumentNotValidException.class)</pre><p>This tells Spring that this method handles MethodArgumentNotValidException.</p><p>This exception is raised when individual request-body validation fails in the normal Spring MVC validation path.</p><h3>getBindingResult()</h3><pre>ex.getBindingResult()</pre><p>This retrieves the validation result containing information about the errors.</p><h3>getFieldErrors()</h3><pre>ex.getBindingResult().getFieldErrors()</pre><p>This retrieves field-level validation errors.</p><p>For example, if the email is missing, the validation provider has information such as:</p><pre>Field: email<br>Message: Email is required</pre><h3>getDefaultMessage()</h3><pre>error.getDefaultMessage()</pre><p>This retrieves the custom message we specified in the validation annotation.</p><p>Finally:</p><pre>return ResponseEntity.badRequest().body(errors);</pre><p>We return HTTP 400 along with the validation errors.</p><p>An example response could be:</p><pre>{<br>    &quot;name&quot;: &quot;Name is required&quot;,<br>    &quot;email&quot;: &quot;Email is required&quot;,<br>    &quot;dateOfBirth&quot;: &quot;Date of birth is required&quot;<br>}</pre><p>Now clients can understand exactly what went wrong.</p><p>Note that a simple Map stores one message per field. For applications that need to return multiple messages for the same field, use a list of error objects instead.</p><h3>12. Difference Between @Valid and @Validated</h3><p>This is another common interview question.</p><p>Both annotations can trigger Bean Validation in Spring MVC, but they have different purposes.</p><p>@Valid@ValidatedPart of Jakarta ValidationProvided by SpringDoes not specify groups directlySupports specifying validation groupsUses the Default group when used normallyCan select a custom groupUseful for standard validationUseful for grouped validation</p><p>For example:</p><p>Normal validation:</p><pre>@Valid<br>@RequestBody PatientRequestDTO patientDTO</pre><p>Custom group validation:</p><pre>@Validated(CreatePatientValidationGroup.class)<br>@RequestBody PatientRequestDTO patientDTO</pre><p>Remember:</p><ul><li>Use @Valid when you want ordinary Default group validation.</li><li>Use @Validated when you want to select a particular validation group.</li></ul><p>They can also work together with nested DTO validation, but for our controller parameters, @Validated is sufficient to trigger the selected group.</p><h3>13. Are Validation Groups Always Better Than Separate DTOs?</h3><p>No.</p><p>This is an important design decision.</p><p>Validation Groups are useful, but they are not a replacement for every DTO design.</p><p>Consider these two approaches.</p><h3>Approach A: Separate DTOs</h3><pre>CreatePatientRequestDTO<br>UpdatePatientRequestDTO</pre><p>Each DTO has its own fields and validation annotations.</p><p>Advantages:</p><ul><li>Clear separation between operations.</li><li>Each request structure is easy to understand.</li><li>Different operations can have completely different fields.</li></ul><p>Disadvantages:</p><ul><li>Some fields and validation rules may need to be repeated.</li><li>More DTO classes to maintain.</li></ul><h3>Approach B: Validation Groups</h3><pre>PatientRequestDTO</pre><p>The same DTO is reused with different validation groups.</p><p>Advantages:</p><ul><li>Less duplication when request structures are similar.</li><li>Validation rules are organized by operation.</li><li>Easier reuse of common constraints.</li></ul><p>Disadvantages:</p><ul><li>The DTO can become more complicated when many groups are introduced.</li><li>It can be harder to understand which constraints apply to a specific operation.</li></ul><p>My takeaway:</p><p>Use Validation Groups when the same request structure is shared across operations but certain validation requirements differ.</p><p>Use separate DTOs when the request structures or business requirements are significantly different.</p><p>For example, a registration DTO and a password-reset DTO probably deserve separate request classes.</p><h3>14. Common Mistakes When Using Validation Groups</h3><p>Let’s go through a few mistakes that can cause confusion.</p><h3>Mistake 1: Creating an interface but not assigning constraints to it</h3><p>Creating this interface alone does not change anything:</p><pre>public interface CreatePatientValidationGroup {<br>}</pre><p>We must associate constraints with it:</p><pre>@NotBlank(groups = CreatePatientValidationGroup.class)<br>private String name;</pre><p>Otherwise, the interface has no custom validation rules associated with it.</p><h3>Mistake 2: Forgetting the Default group</h3><p>Consider:</p><pre>@NotBlank<br>private String name;</pre><p>And:</p><pre>@Validated(CreatePatientValidationGroup.class)</pre><p>If the custom group does not inherit from Default, the name constraint will not execute.</p><p>Either explicitly assign the constraint to the custom group or make the custom group extend Default.</p><h3>Mistake 3: Thinking @Email makes a field mandatory</h3><p>This is incorrect:</p><pre>@Email<br>private String email;</pre><p>It checks the email format, but it does not make the value mandatory.</p><p>Use:</p><pre>@NotBlank<br>@Email<br>private String email;</pre><p>when the email must be provided.</p><h3>Mistake 4: Thinking groups automatically define execution order</h3><p>Validation Groups do not automatically mean that one group executes before another.</p><p>They identify subsets of constraints.</p><p>If we need to control validation order, Jakarta Bean Validation provides @GroupSequence.</p><p>For example, we may want basic validation to pass before running more expensive validation checks.</p><h3>Mistake 5: Thinking DTO validation replaces business validation</h3><p>Consider checking whether an email already exists in the database.</p><p>This is not simply a format-validation problem.</p><p>Even if an email has a valid format, it may already belong to another patient.</p><p>We should enforce that business rule using the appropriate service or domain logic, usually with a database uniqueness constraint as an additional safeguard.</p><p>Bean Validation and business validation solve different problems.</p><h3>15. When Should You Use Validation Groups?</h3><p>Validation Groups are useful in situations such as:</p><p><strong>User registration and profile updates</strong></p><p>A password may be mandatory during registration but optional when updating a profile.</p><p><strong>Create and update operations</strong></p><p>A create request may require every field, whereas an update request may allow selected fields to be omitted.</p><p><strong>Different workflow stages</strong></p><p>An object may need to satisfy different sets of rules at different stages of its lifecycle.</p><p><strong>Reusable request objects</strong></p><p>When several operations share a DTO but have slightly different validation requirements, groups can prevent unnecessary duplication.</p><h3>Conclusion</h3><p>When I first encountered this concept, I genuinely wondered why we needed an empty interface.</p><p>But after understanding how Validation Groups work, the purpose became clear.</p><p>The interface is not there to implement any functionality.</p><p>It is simply a marker that identifies a particular set of validation constraints.</p><p>The important things to remember are:</p><ol><li>Validation annotations define the actual rules.</li><li>Marker interfaces identify validation groups.</li><li>The groups attribute associates constraints with those groups.</li><li>@Validated tells Spring which group to execute.</li><li>The Default group is used when no group is explicitly specified.</li><li>Custom groups can extend Default to include common constraints.</li></ol><p>The biggest lesson for me was this:</p><p><strong>Validation is not only about checking whether data is valid. It is also about deciding which rules should apply at a particular point in the application’s workflow.</strong></p><p>And that is exactly what Validation Groups help us achieve.</p><h3>References and Further Reading</h3><ul><li>Jakarta Bean Validation Specification: <a href="https://jakarta.ee/specifications/bean-validation/">https://jakarta.ee/specifications/bean-validation/</a></li><li>Spring Framework — Java Bean Validation: <a href="https://docs.spring.io/spring-framework/reference/core/validation/beanvalidation.html">https://docs.spring.io/spring-framework/reference/core/validation/beanvalidation.html</a></li><li>Spring Framework — MVC Controller Validation: <a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-validation.html">https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-validation.html</a></li></ul><p><em>Thanks for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30cf379ad1e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Says “Exactly Once.” What Actually Happens When a Message Is Retried?]]></title>
            <link>https://medium.com/@unknown0149/kafka-says-exactly-once-what-actually-happens-when-a-message-is-retried-3271e4f868e2?source=rss-6a30a2fdc261------2</link>
            <guid isPermaLink="false">https://medium.com/p/3271e4f868e2</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Aryan Chauhan]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 10:40:54 GMT</pubDate>
            <atom:updated>2026-11-01T10:40:54.028Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One lost acknowledgement can create duplicate messages. One consumer crash can repeat an entire operation. Here’s how Kafka uses producer IDs, sequence numbers, transactions, and offset management to handle these failures — with Java and Spring Boot examples.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxKbG_lhCNJlH_KosqFLRQ.png" /></figure><p>Imagine you’re building a payment processing system.</p><p>A customer makes a payment of ₹5,000. Your Spring Boot application publishes a PaymentCompleted event to Apache Kafka.</p><p>The broker receives the message, writes it to a partition, and sends an acknowledgement (ACK) back to the producer.</p><p>But something goes wrong.</p><p>The message is successfully stored. The broker sends the ACK. Unfortunately, the network fails before the producer receives it.</p><p>What happens now?</p><p>The producer doesn’t know whether the message was stored or not. From its perspective, both possibilities are equally plausible.</p><p>So it retries.</p><p>But the original message is already inside Kafka. If the broker treats the retry as a completely new message, the same payment event gets written twice.</p><p>Now imagine another failure.</p><p>A consumer reads the payment event, processes it, and publishes the result to another topic. Just before committing its offset, the consumer crashes.</p><p>When it restarts, Kafka delivers the same event again.</p><p>Two different failures, both capable of creating duplicate results.</p><p><strong>How does Kafka make sure that these failures don’t leave behind duplicate committed results?</strong></p><p>This is where <em>Exactly-Once Semantics (EOS)</em> comes in.</p><p>The interesting part is that Kafka doesn’t solve this using one magic setting. It combines several mechanisms, each handling a different failure scenario.</p><p>Let’s understand how they work together.</p><h3>1. First, Understand Why Exactly-Once Is Difficult</h3><p>Before looking at Kafka’s implementation, consider the three common message delivery guarantees.</p><p><strong>At-most-once:</strong> A message is processed zero or one times. If the application crashes at the wrong moment, the message may be lost.</p><p><strong>At-least-once:</strong> The application retries until processing succeeds. Messages may be delivered more than once.</p><p><strong>Exactly-once:</strong> The committed result of a supported processing operation becomes visible once, even when the application encounters failures and retries.</p><p>Why is the third one difficult?</p><p>Consider a consumer processing an event at offset 105.</p><p>There are two ways to manage its progress.</p><p><strong>Approach A: Commit before processing</strong></p><p>The consumer commits offset 106 and then processes the event.</p><p>If it crashes immediately after committing the offset, Kafka assumes the event has already been handled. But the application never finished processing it.</p><p>The message is effectively skipped.</p><p><strong>Approach B: Process before committing</strong></p><p>The consumer processes the event and then commits offset 106.</p><p>If it crashes between these two operations, Kafka redelivers offset 105.</p><p>The business logic runs again.</p><p>This is the fundamental problem: <em>there is no guarantee that processing and saving progress happen together.</em></p><p>Kafka’s transactional mechanism addresses this for Kafka-to-Kafka workflows by coordinating the output records and consumed offsets in one transaction.</p><p>But first, let’s solve the producer-side problem.</p><h3>2. Idempotent Producer: How Does Kafka Recognize a Duplicate Retry?</h3><p>Let’s return to our lost acknowledgement.</p><p>The producer sends a batch to Kafka. The broker stores it, but the ACK never reaches the producer.</p><p>The producer retries the same batch.</p><p>How does the broker know that the second request is a retry rather than a new message?</p><p>Kafka uses two important pieces of information:</p><ul><li><strong>Producer ID (PID)</strong></li><li><strong>Sequence Number</strong></li></ul><p>When an idempotent producer initializes, Kafka assigns it a unique Producer ID.</p><p>The producer also maintains sequence numbers for the batches it sends to each partition.</p><p>Consider this example.</p><p>The producer sends:</p><pre>Producer ID : 42<br>Partition   : 0<br>Sequence    : 15<br>Message     : PAYMENT_101</pre><p>Kafka accepts the batch, stores it, and remembers the producer’s sequence information.</p><p>The ACK gets lost.</p><p>The producer retries the same batch:</p><pre>Producer ID : 42<br>Partition   : 0<br>Sequence    : 15<br>Message     : PAYMENT_101</pre><p>The broker recognizes that it has already accepted this producer sequence for that partition.</p><p><strong>It does not append another copy of the batch.</strong></p><p>This is how Kafka handles the ambiguous outcome of a lost acknowledgement.</p><p>The broker doesn’t need to search through the topic and compare the JSON of every existing message. It uses producer identity and sequence tracking.</p><p>The sequence numbers also help the broker detect unexpected or out-of-order batches rather than blindly accepting them.</p><h3>Let’s see it in Java</h3><pre>Properties props = new Properties();</pre><pre>props.put(<br>    ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,<br>    &quot;localhost:9092&quot;<br>);</pre><pre>props.put(<br>    ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,<br>    StringSerializer.class.getName()<br>);</pre><pre>props.put(<br>    ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,<br>    StringSerializer.class.getName()<br>);</pre><pre>props.put(<br>    ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG,<br>    true<br>);</pre><pre>props.put(<br>    ProducerConfig.ACKS_CONFIG,<br>    &quot;all&quot;<br>);</pre><pre>KafkaProducer&lt;String, String&gt; producer =<br>    new KafkaProducer&lt;&gt;(props);</pre><p>Modern Kafka producers enable idempotence by default when compatible configurations are used. I’ve enabled it explicitly here to show what the application expects.</p><p>There is one important limitation.</p><p>Idempotent producers protect against duplicate retries made by the Kafka producer protocol. They do not identify two independent application requests as the same business operation.</p><p>For example, if your application calls send() twice independently with the same payment ID, Kafka may accept both messages.</p><p><em>Producer idempotence prevents duplicate transport retries, not every possible business-level duplicate.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYHr3j6lIR4lPX2_tA1rcA.png" /></figure><p>3. Acknowledgements and Replication: What If the Broker Crashes?</p><p>Preventing duplicate writes is one problem. Making sure an acknowledged message survives a broker failure is another.</p><p>Kafka stores messages in partitions, and partitions can be replicated across multiple brokers.</p><p>Suppose a partition has three replicas:</p><ul><li>Broker 1: Leader</li><li>Broker 2: Follower</li><li>Broker 3: Follower</li></ul><p>The producer sends the message to the leader.</p><p>The leader writes the record and replication takes place among the in-sync replicas (ISR).</p><p>Now consider this producer configuration:</p><pre>props.put(<br>    ProducerConfig.ACKS_CONFIG,<br>    &quot;all&quot;<br>);</pre><p>With acks=all, the leader waits for acknowledgements from the current in-sync replicas before responding to the producer.</p><p>We can also configure the broker or topic with:</p><pre>min.insync.replicas=2</pre><p>This requires at least two in-sync replicas for an acks=all write to succeed.</p><p>Why is that useful?</p><p>Suppose the leader crashes immediately after acknowledging the message.</p><p>If the acknowledged record has been replicated to the in-sync replicas, an eligible surviving replica can take over without losing that record, assuming an appropriate in-sync replica remains available.</p><p>There is an important distinction:</p><ul><li>acks=all controls when the producer receives an acknowledgement.</li><li>min.insync.replicas controls the minimum number of in-sync replicas required for the write.</li></ul><p>Also, acks=all means the current ISR, not every replica originally configured for the partition.</p><p><strong>Replication protects the durability of acknowledged messages. Idempotence protects against duplicate producer retries.</strong></p><p>They work together to make publishing more reliable, but replication alone is not exactly-once processing.</p><h3>4. Producer Epochs: What Happens When an Old Producer Comes Back?</h3><p>Now imagine a different failure.</p><p>Your payment service becomes unresponsive because of a network partition.</p><p>Your deployment system starts a replacement instance. But the old instance hasn’t completely stopped.</p><p>Now two producer instances might attempt to perform the same logical work.</p><p>How does Kafka prevent the old producer from interfering with the replacement?</p><p>This is where <strong>transactional IDs and producer epochs</strong> become important.</p><p>A transactional producer has an identity called transactional.id.</p><p>For example:</p><pre>props.put(<br>    ProducerConfig.TRANSACTIONAL_ID_CONFIG,<br>    &quot;payment-service-worker-1&quot;<br>);</pre><p>When the producer calls:</p><pre>producer.initTransactions();</pre><p>Kafka initializes its transactional state and associates the producer with an ID and an epoch.</p><p>Think of an epoch as a generation number.</p><p>Suppose the older producer has:</p><pre>Producer ID : 42<br>Epoch       : 3</pre><p>A replacement producer initializes using the same transactional ID.</p><p>Kafka assigns the replacement a newer epoch.</p><p>The old producer is now considered stale. If it tries to continue making transactional writes, Kafka fences it out.</p><p>This is called <strong>producer fencing</strong>.</p><p>It prevents an older producer from continuing to act as the active owner of that transactional identity.</p><p>There’s another important benefit of a stable transactional ID.</p><p>Kafka can identify unfinished transactions from a previous producer session and resolve them when a replacement producer initializes.</p><p>This is why transactional.id is different from an ordinary producer ID. It allows Kafka to preserve transactional identity across producer sessions.</p><p>For multiple running application instances, each instance needs a unique transactional identity. When recovering the same logical instance, the identity should be reused so its previous producer can be fenced.</p><h3>5. Kafka Transactions: How Does It Coordinate the Consumer and Producer?</h3><p>So far, we’ve handled producer-side failures.</p><p>Now let’s look at the consumer.</p><p>Imagine this workflow:</p><p>A consumer reads an event from the payments topic, processes it, and publishes the result to processed-payments.</p><p>There are two separate operations:</p><ol><li>Write the output record.</li><li>Commit the consumed input offset.</li></ol><p>What happens if the output is successfully written but the consumer crashes before committing the input offset?</p><p>Kafka redelivers the input record.</p><p>The consumer processes it again.</p><p>The result can be published twice.</p><p>This is where <strong>Kafka Transactions</strong> become important.</p><p>A transactional producer can include both the output records and the consumed offsets in one atomic operation.</p><p>The workflow looks like this:</p><ol><li>Consumer reads an event.</li><li>Application processes the event.</li><li>Producer begins a transaction.</li><li>Producer publishes the output.</li><li>Producer adds the consumed input offset to the transaction.</li><li>Producer commits the transaction.</li></ol><p>The output records and input offsets are committed together.</p><p><strong>Either both are committed, or neither is committed.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftSGX5nUo3ftJsXWDnl8Jg.png" /></figure><h3>Implementing this using Java</h3><p>First, configure a transactional producer:</p><pre>props.put(<br>    ProducerConfig.TRANSACTIONAL_ID_CONFIG,<br>    &quot;payment-processor-instance-1&quot;<br>);</pre><pre>KafkaProducer&lt;String, String&gt; producer =<br>    new KafkaProducer&lt;&gt;(props);</pre><pre>producer.initTransactions();</pre><p>The consumer must not commit offsets automatically:</p><pre>consumerProps.put(<br>    ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,<br>    false<br>);</pre><pre>consumerProps.put(<br>    ConsumerConfig.ISOLATION_LEVEL_CONFIG,<br>    &quot;read_committed&quot;<br>);</pre><p>Now let’s look at the core consume-process-produce operation:</p><pre>ConsumerRecords&lt;String, String&gt; records =<br>    consumer.poll(Duration.ofMillis(500));</pre><pre>Map&lt;TopicPartition, OffsetAndMetadata&gt; offsets =<br>    new HashMap&lt;&gt;();</pre><pre>producer.beginTransaction();</pre><pre>try {</pre><pre>    for (ConsumerRecord&lt;String, String&gt; record : records) {</pre><pre>        String result = processPayment(record.value());</pre><pre>        producer.send(<br>            new ProducerRecord&lt;&gt;(<br>                &quot;processed-payments&quot;,<br>                record.key(),<br>                result<br>            )<br>        );</pre><pre>        TopicPartition partition =<br>            new TopicPartition(<br>                record.topic(),<br>                record.partition()<br>            );</pre><pre>        offsets.put(<br>            partition,<br>            new OffsetAndMetadata(record.offset() + 1)<br>        );<br>    }</pre><pre>    producer.sendOffsetsToTransaction(<br>        offsets,<br>        consumer.groupMetadata()<br>    );</pre><pre>    producer.commitTransaction();</pre><pre>} catch (KafkaException e) {</pre><pre>    producer.abortTransaction();</pre><pre>    // Reset the consumer to committed offsets before<br>    // attempting to process the records again.</pre><pre>    throw e;<br>}</pre><p><em>This is a simplified illustration of the transaction flow, not a complete production consumer. Real applications must distinguish fatal producer errors from abortable failures, restore consumer position after an abort, and handle rebalances and resource cleanup.</em></p><p>Let’s focus on the most important method:</p><pre>producer.sendOffsetsToTransaction(<br>    offsets,<br>    consumer.groupMetadata()<br>);</pre><p>Normally, consumers commit offsets independently.</p><p>Here, we’re asking Kafka to include those offsets in the producer’s current transaction.</p><p>Notice that the code uses:</p><pre>record.offset() + 1</pre><p>Kafka stores the <em>next offset to consume</em>, not the offset of the last record processed.</p><p>Now suppose the application crashes before commitTransaction().</p><p>The output transaction does not become committed, and the consumed offsets are not advanced by that transaction.</p><p>The input event can be processed again.</p><p>When a successful transaction eventually commits, the output and the corresponding offsets become committed together.</p><p><strong>The processing code can execute more than once. The important guarantee is that an aborted attempt does not become an additional committed Kafka output.</strong></p><p>That is the heart of Kafka’s exactly-once processing.</p><h3>6. Transaction Coordinator: Who Makes This Atomic?</h3><p>A natural question follows.</p><p>If a Kafka transaction writes to multiple partitions hosted on different brokers, who coordinates the operation?</p><p>Kafka uses a component called the <strong>Transaction Coordinator</strong>.</p><p>It manages the state of a transactional producer.</p><p>Kafka stores transaction metadata in an internal topic called:</p><pre>__transaction_state</pre><p>When a transaction begins, the coordinator tracks it. As the producer writes to different partitions, those partitions become participants in the transaction.</p><p>When the producer requests a commit or abort, the coordinator manages the decision and coordinates the participating partitions.</p><p>Kafka then writes transaction markers to those partitions so consumers can determine whether the transactional records belong to a committed or aborted transaction.</p><p>Why is this necessary?</p><p>Because the output topic and the internal consumer-offset data may be hosted on different brokers.</p><p>Kafka needs to make sure they share one consistent transaction outcome.</p><p><strong>The Transaction Coordinator is responsible for coordinating that outcome across the participating partitions.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXujM00rAeQinF5BXFOGHg.png" /></figure><h3>7. read_committed: How Does Kafka Hide Aborted Messages?</h3><p>Imagine a producer writes an output record inside a transaction, but the transaction is eventually aborted.</p><p>The record may still physically exist in the Kafka log.</p><p>How does Kafka prevent a downstream consumer from treating it as successful output?</p><p>Kafka provides two consumer isolation levels:</p><pre>isolation.level=read_uncommitted</pre><p>and:</p><pre>isolation.level=read_committed</pre><p>With read_uncommitted, consumers can see records belonging to aborted transactions.</p><p>With read_committed, consumers only see records from committed transactions, along with eligible non-transactional records.</p><p>This matters because <strong>a record being written to Kafka does not necessarily mean its transaction has committed.</strong></p><p>Kafka also maintains something called the <em>Last Stable Offset (LSO)</em>.</p><p>A read_committed consumer cannot read beyond the point where an earlier transaction in that partition is still unresolved.</p><p>This ensures that records from unfinished transactions are not exposed prematurely.</p><p>There is also a performance implication: an open transaction can delay the visibility of later records in the same partition.</p><p>The consumer configuration is straightforward:</p><pre>consumerProps.put(<br>    ConsumerConfig.ISOLATION_LEVEL_CONFIG,<br>    &quot;read_committed&quot;<br>);</pre><p>This is the final piece that allows downstream consumers to observe only committed transactional results.</p><h3>8. How Does Spring Boot Handle Exactly-Once Processing?</h3><p>The Java examples above show how Kafka’s transaction API works directly.</p><p>But in a Spring Boot application, you usually don’t want to manually manage beginTransaction(), sendOffsetsToTransaction(), and commitTransaction() inside every listener.</p><p>Spring for Apache Kafka provides transaction support through:</p><ul><li>KafkaTransactionManager</li><li>KafkaTemplate</li><li>Transactional listener containers</li></ul><p>With Spring Boot, providing a transactional producer ID prefix automatically configures a Kafka transaction manager and wires it into the listener container.</p><h3>Step 1: Configure Spring Boot</h3><p>Add these properties to application.properties:</p><pre>spring.kafka.bootstrap-servers=localhost:9092</pre><pre>spring.kafka.producer.acks=all</pre><pre>spring.kafka.producer.transaction-id-prefix=${INSTANCE_ID}-payments-</pre><pre>spring.kafka.producer.properties[enable.idempotence]=true</pre><pre>spring.kafka.consumer.enable-auto-commit=false</pre><pre>spring.kafka.consumer.properties[isolation.level]=read_committed</pre><p>The important property is:</p><pre>spring.kafka.producer.transaction-id-prefix=${INSTANCE_ID}-payments-</pre><p>Spring uses this prefix to create transactional producer IDs.</p><p><strong>Every concurrently running application instance must have a unique prefix.</strong> Reusing the same logical identity during recovery allows the previous producer to be fenced.</p><h3>Step 2: Create a Kafka producer using KafkaTemplate</h3><pre>@Service<br>public class PaymentProducer {</pre><pre>    private final KafkaTemplate&lt;String, PaymentProcessed&gt;<br>            kafkaTemplate;</pre><pre>    public PaymentProducer(<br>        KafkaTemplate&lt;String, PaymentProcessed&gt; kafkaTemplate<br>    ) {<br>        this.kafkaTemplate = kafkaTemplate;<br>    }</pre><pre>    public void publish(String paymentId, String status) {</pre><pre>        PaymentProcessed event =<br>            new PaymentProcessed(paymentId, status);</pre><pre>        kafkaTemplate.send(<br>            &quot;processed-payments&quot;,<br>            paymentId,<br>            event<br>        );<br>    }<br>}</pre><h3>Step 3: Consume and process the event</h3><pre>@Service<br>public class PaymentConsumer {</pre><pre>    private final PaymentProducer paymentProducer;</pre><pre>    public PaymentConsumer(PaymentProducer paymentProducer) {<br>        this.paymentProducer = paymentProducer;<br>    }</pre><pre>    @KafkaListener(<br>        topics = &quot;payments&quot;,<br>        groupId = &quot;payment-processor&quot;<br>    )<br>    public void processPayment(PaymentEvent payment) {</pre><pre>        String status = processBusinessLogic(payment);</pre><pre>        paymentProducer.publish(<br>            payment.getPaymentId(),<br>            status<br>        );<br>    }<br>}</pre><p>The listener itself is simple. The important part happens inside Spring’s listener container.</p><p>When configured with the Kafka transaction manager:</p><ol><li>Spring starts a Kafka transaction before invoking the listener.</li><li>The consumer receives the event.</li><li>The listener executes the business logic.</li><li>KafkaTemplate publishes the output using the transactional producer.</li><li>If the listener completes successfully, Spring adds the consumed offsets to the transaction.</li><li>Spring commits the transaction.</li></ol><p>If the listener throws an exception, the transaction is rolled back and the consumer is repositioned so that the record can be retrieved again.</p><p><strong>You do not need to manually call </strong><strong>sendOffsetsToTransaction() in this listener example. Spring&#39;s transactional listener container handles it.</strong></p><p>One important distinction: the business logic can still execute again after a rollback. Spring’s exactly-once guarantee applies to the committed read → process → write result, not to executing the Java method only once.</p><h3>9. Does Exactly-Once Guarantee Work with PostgreSQL and External APIs?</h3><p>This is where Kafka’s guarantee reaches its boundary.</p><p>Consider this architecture:</p><pre>Kafka<br>  |<br>  v<br>Spring Boot Consumer<br>  |<br>  v<br>PostgreSQL</pre><p>The consumer receives a payment event and updates PostgreSQL.</p><p>The database transaction commits successfully.</p><p>But before committing the Kafka offset, the application crashes.</p><p>Kafka redelivers the event.</p><p>PostgreSQL may receive the same business operation again.</p><p>Why doesn’t Kafka roll back the database update?</p><p>Because Kafka’s transaction coordinator manages Kafka transactions. An ordinary PostgreSQL transaction is managed separately.</p><p>The two systems do not automatically participate in one atomic transaction.</p><p>For external systems, applications need additional protection, such as:</p><p><strong>Inbox Pattern:</strong> Store processed event IDs in a database table with a unique constraint. Apply the business update only when the event ID is inserted for the first time. Both operations must happen in the same database transaction.</p><p><strong>Transactional Outbox:</strong> Save the business data and the corresponding event in the same database transaction. A separate relay or CDC process publishes the outbox event to Kafka. The downstream consumer should still be idempotent because the relay can publish more than once.</p><p>The key takeaway is that Kafka’s exactly-once guarantee is strongest for Kafka-to-Kafka processing. Extending it to databases and APIs requires those systems to cooperate.</p><h3>10. So, What Actually Makes Kafka’s Exactly-Once Semantics Work?</h3><p>Let’s connect all the mechanisms.</p><p>Failure or problemMechanismACK gets lostIdempotent producerProducer retries a batchProducer ID and sequence numbersBroker failsReplication and acks=allOld producer continues after restartProducer epoch and fencingOutput and input offset must agreeKafka transactionsMultiple brokers participateTransaction CoordinatorAborted output must remain invisibleread_committed</p><p>Each mechanism solves a different part of the problem.</p><p>Idempotence prevents duplicate producer retry writes.</p><p>Replication improves the durability of acknowledged records.</p><p>Fencing prevents stale producers from interfering with newer instances.</p><p>Transactions coordinate output records with consumed offsets.</p><p>And read_committed ensures downstream consumers only see committed transactional results.</p><p><strong>Exactly-once semantics is not one feature or one configuration property. It is the result of multiple mechanisms working together within a defined transactional boundary.</strong></p><h3>Final Thoughts</h3><p>The most interesting thing about Kafka’s design is that it doesn’t assume failures won’t happen.</p><p>It assumes that acknowledgements can disappear, brokers can fail, producers can restart, and consumers can crash after processing a message.</p><p>Instead of trying to prevent every failure, Kafka uses producer identity, sequence tracking, replication, fencing, transaction coordination, and offset management to make recovery possible without exposing duplicate committed results.</p><p>The lesson is simple:</p><p><em>You cannot always prevent an operation from being attempted more than once. But you can design a system where retries do not create duplicate committed results.</em></p><p>That’s what makes Kafka’s Exactly-Once Semantics interesting from a distributed-systems perspective.</p><h3>Further Reading</h3><ul><li><a href="https://kafka.apache.org/43/design/design/">Apache Kafka — Design and Message Delivery Semantics</a></li><li><a href="https://kafka.apache.org/43/configuration/producer-configs/">Apache Kafka — Producer Configuration</a></li><li><a href="https://kafka.apache.org/43/operations/transaction-protocol/">Apache Kafka — Transaction Protocol</a></li><li><a href="https://docs.spring.io/spring-kafka/reference/kafka/exactly-once.html">Spring for Apache Kafka — Exactly-Once Semantics</a></li><li><a href="https://docs.spring.io/spring-kafka/reference/kafka/transactions.html">Spring for Apache Kafka — Transaction</a>s</li></ul><p><em>What do you think is the hardest part of building reliable distributed systems: handling retries, recovering from failures, or coordinating transactions across multiple services?</em></p><p>#ApacheKafka #Java #SpringBoot #DistributedSystems #SystemDesign #BackendEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3271e4f868e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Has a Stack Class. So Why Do Developers Prefer ArrayDeque?]]></title>
            <link>https://medium.com/@unknown0149/java-has-a-stack-class-so-why-do-developers-prefer-arraydeque-ebdc2f95119f?source=rss-6a30a2fdc261------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebdc2f95119f</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aryan Chauhan]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 10:28:19 GMT</pubDate>
            <atom:updated>2026-10-30T10:28:19.696Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s something interesting about Java.</p><p>Java already provides a class called Stack. So naturally, when we need a stack, we write:</p><pre>Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();</pre><p>Makes sense, right?</p><p>But there’s a catch.</p><p><strong>Java’s own documentation recommends using </strong><strong>Deque implementations instead of the legacy </strong><strong>Stack class.</strong></p><p>And the interesting part is <em>why</em>.</p><p>Let’s understand what’s happening behind the scenes.</p><h3>1. The problem starts with Vector</h3><p>Look at the declaration of Java’s Stack:</p><pre>public class Stack&lt;E&gt; extends Vector&lt;E&gt;</pre><p>Yes. Stack extends Vector.</p><p>And Vector is a legacy collection in Java where methods are synchronized.</p><p>What does synchronization actually mean?</p><p>Imagine two threads trying to modify the same collection simultaneously.</p><p>One thread wants to add an element while another wants to remove one.</p><p>Java needs a way to coordinate access so that threads don’t interfere with each other.</p><p>That’s what synchronization does.</p><p>A synchronized method acquires an object’s monitor lock before executing.</p><p>Now think about a typical coding problem.</p><p>You’re implementing a monotonic stack, performing thousands of push and pop operations, and running everything in a single thread.</p><p><strong>Do you really need synchronization?</strong></p><p>Usually, no.</p><p>Here’s what happens internally:</p><ul><li>Stack.push() delegates to Vector&#39;s synchronized addElement().</li><li>Stack.pop() is synchronized.</li><li>Stack.peek() is synchronized.</li></ul><p>So your simple stack operations carry synchronization-related overhead.</p><p>It’s not necessarily a huge cost every time, because the JVM can optimize synchronization. But it’s additional machinery that a typical single-threaded stack doesn’t need.</p><h3>2. Enter ArrayDeque</h3><p>Instead of using the legacy Stack class, Java gives us another option:</p><pre>Deque&lt;Integer&gt; stack = new ArrayDeque&lt;&gt;();</pre><p>The syntax is almost identical.</p><pre>stack.push(10);<br>stack.push(20);<br>stack.push(30);</pre><pre>System.out.println(stack.peek()); // 30</pre><pre>stack.pop();</pre><p>But internally, things are different.</p><p><strong>ArrayDeque uses a resizable circular array.</strong></p><p>It maintains indexes to manage elements at both ends of the array.</p><p>When you call:</p><ul><li>push() → inserts at the front.</li><li>pop() → removes from the front.</li><li>peek() → reads from the front.</li></ul><p>No synchronization locks are used for these normal operations.</p><p>This makes ArrayDeque particularly suitable for single-threaded stack and queue implementations.</p><h3>3. But wait… both have O(1) operations!</h3><p>This is where things get interesting.</p><p>OperationStackArrayDequePushO(1) amortizedO(1) amortizedPopO(1)O(1)PeekO(1)O(1)SynchronizedYesNo</p><p>So how can one be faster when both have the same time complexity?</p><p><strong>Because Big-O doesn’t tell the entire performance story.</strong></p><p>It tells us how execution time grows with input size. It doesn’t tell us exactly how much work happens inside each operation.</p><p>Think of it this way:</p><p>Two people can reach the same destination, but one might take a route with unnecessary stops.</p><p>Both routes work. One simply does more work.</p><p>That’s the idea here.</p><p>ArrayDeque avoids synchronization overhead and is specifically designed around efficient double-ended operations.</p><p>One misconception worth clearing up: Stack and ArrayDeque are <em>both array-backed</em>. The difference isn’t array versus linked list. It’s their implementation and synchronization behaviour.</p><h3>4. Let’s see this in a real coding problem</h3><p>I tested the difference using <strong>LeetCode 739 — Daily Temperatures</strong>.</p><p>It’s a classic Monotonic Stack problem.</p><p>The interesting thing is that we don’t need to change the algorithm at all.</p><p>With Stack:</p><pre>Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();</pre><p>With ArrayDeque:</p><pre>Deque&lt;Integer&gt; stack = new ArrayDeque&lt;&gt;();</pre><p>That’s the only change to the collection initialization.</p><p>The same push, pop, peek operations. The same algorithm. The same O(n) time complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIVxkWXlfr-oSLNbGiF6kA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNPrEU7BN8eP7IZRYAkqmw.png" /></figure><p>The execution times can differ, although LeetCode timings fluctuate between runs. So don’t treat one submission as a scientific benchmark.</p><p>The point is simple:</p><p><em>Your algorithm isn’t always the only thing affecting performance. Your implementation choices matter too.</em></p><h3>5. So, what should you use?</h3><p>For most single-threaded stack problems in Java, use:</p><pre>Deque&lt;Integer&gt; stack = new ArrayDeque&lt;&gt;();</pre><p>It’s a great choice for:</p><ul><li>Monotonic Stack</li><li>Next Greater Element</li><li>Daily Temperatures</li><li>Valid Parentheses</li><li>DFS</li><li>Expression Evaluation</li></ul><p>Just remember that ArrayDeque isn’t thread-safe and doesn’t allow null elements. For concurrent access, choose a suitable concurrent collection.</p><h3>The takeaway</h3><p>We spend so much time learning data structures and their time complexities that we sometimes forget to understand their internal implementations.</p><p>Knowing <em>when</em> to use a stack is important.</p><p>Knowing <em>which implementation</em> to use is important too.</p><p>Sometimes, optimization doesn’t mean rewriting your entire algorithm.</p><p><strong>Sometimes, it starts with understanding one line of code.</strong></p><p>Happy coding! ☕</p><p><strong>Further reading:</strong></p><ul><li><a href="https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/util/Stack.html">Stack — Java Documentation</a></li><li><a href="https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/util/ArrayDeque.html">ArrayDeque — Java Documentation</a></li><li><a href="https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/ArrayDeque.java">ArrayDeque — OpenJDK Source Code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebdc2f95119f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java ThreadPoolExecutor: What Happens When Your Application Gets Too Many Tasks?]]></title>
            <link>https://medium.com/@unknown0149/java-threadpoolexecutor-what-happens-when-your-application-gets-too-many-tasks-f09c05780f2b?source=rss-6a30a2fdc261------2</link>
            <guid isPermaLink="false">https://medium.com/p/f09c05780f2b</guid>
            <dc:creator><![CDATA[Aryan Chauhan]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 13:53:56 GMT</pubDate>
            <atom:updated>2026-10-28T13:53:56.316Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding multithreading, thread pools, task queues, and rejection policies through real Java examples.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5MxGfDXuB8vEimfElcIPA.png" /></figure><p>Imagine you’ve just built a backend service that processes user uploads, generates PDF reports, and sends email notifications.</p><p>Everything works perfectly on your laptop. Requests are fast, the application feels responsive, and you’re happy with the result.</p><p>Then you deploy to production.</p><p>Suddenly, hundreds of requests start arriving at the same time. Users are uploading files, generating reports, and triggering background tasks simultaneously.</p><p>Your first instinct might be:</p><p><em>“Why not just create a new thread for every task? More threads should mean more work gets done, right?”</em></p><p>Not exactly.</p><p>Threads consume memory and other system resources. They also compete for CPU time. Creating more threads than your application can handle increases overhead and can eventually exhaust available resources.</p><p>The real challenge isn’t learning how to create threads. <strong>It’s learning how to manage thousands of tasks without creating thousands of threads.</strong></p><p>That’s where Java’s ThreadPoolExecutor comes in.</p><p>Let’s understand what happens inside a thread pool, why certain configurations can cause problems, and how to control the amount of work your application accepts.</p><h3>1. A Task Is Not a Thread</h3><p>Before understanding thread pools, we need to clear up a common misconception.</p><p>A <strong>task is the work</strong>. A <strong>thread is what executes the work</strong>.</p><p>Consider this simple Java program:</p><pre>public class Main {</pre><pre>    public static void main(String[] args) {</pre><pre>        Thread emailThread = new Thread(() -&gt;<br>            System.out.println(&quot;Sending email&quot;)<br>        );</pre><pre>        Thread reportThread = new Thread(() -&gt;<br>            System.out.println(&quot;Generating report&quot;)<br>        );</pre><pre>        emailThread.start();<br>        reportThread.start();<br>    }<br>}</pre><p>We created two threads to execute two different tasks.</p><p>But imagine doing this for 10,000 emails.</p><p>Creating a new thread for every email might work in a small experiment, but it’s rarely a sensible default for a heavily loaded backend.</p><p>So, what if we could reuse a small number of threads to handle a large number of tasks?</p><p>Think about a restaurant kitchen with three chefs.</p><p>Orders arrive throughout the day. When a chef finishes one order, they take the next one. If all three chefs are busy, new orders wait in a queue.</p><p>The restaurant doesn’t hire a new chef every time another order arrives.</p><p><strong>A thread pool works in the same way.</strong> It maintains reusable worker threads, while the tasks being executed keep changing.</p><h3>2. Let’s Create Our First Thread Pool</h3><p>Java provides ExecutorService, which lets us submit tasks without manually creating and managing a separate thread for each one.</p><p>Here’s a simple example:</p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;</pre><pre>public class ThreadPoolDemo {</pre><pre>    public static void main(String[] args) {</pre><pre>        ExecutorService executor =<br>                Executors.newFixedThreadPool(3);</pre><pre>        try {<br>            for (int i = 1; i &lt;= 6; i++) {<br>                int taskId = i;</pre><pre>                executor.submit(() -&gt; {<br>                    System.out.println(<br>                        &quot;Task &quot; + taskId<br>                        + &quot; executed by &quot;<br>                        + Thread.currentThread().getName()<br>                    );<br>                });<br>            }<br>        } finally {<br>            executor.shutdown();<br>        }<br>    }<br>}</pre><p>We’re submitting six tasks to a thread pool configured with three worker threads.</p><p>You might see output like this:</p><pre>Task 1 executed by pool-1-thread-1<br>Task 2 executed by pool-1-thread-2<br>Task 3 executed by pool-1-thread-3<br>Task 4 executed by pool-1-thread-1<br>Task 5 executed by pool-1-thread-2<br>Task 6 executed by pool-1-thread-3</pre><p>The actual order, and even the number of workers used for such quick tasks, can vary. But the same worker can execute multiple tasks throughout its lifetime.</p><p>Notice what we didn’t do: create six separate threads.</p><p>We submitted six tasks, and the executor managed their execution.</p><p>One more thing: shutdown() tells the executor to stop accepting new tasks while allowing already-submitted tasks to finish.</p><p>This is convenient, but there’s a problem hiding underneath.</p><p>Executors.newFixedThreadPool(3) uses an <strong>unbounded task queue</strong>. If incoming tasks continuously outpace the workers, pending work can accumulate and consume excessive memory.</p><p>For a more controlled backend, we need to decide how many tasks can execute, how many can wait, and what happens when everything is full.</p><p>That’s where ThreadPoolExecutor becomes useful.</p><h3>3. Meet ThreadPoolExecutor</h3><p>ThreadPoolExecutor is the class that gives us direct control over how a thread pool behaves.</p><p>Instead of simply saying, “Use three threads,” we can configure how the pool grows, where tasks wait, how long extra workers stay alive, and what happens when the pool reaches capacity.</p><p>Consider this configuration:</p><pre>ThreadPoolExecutor executor = new ThreadPoolExecutor(<br>    2,                              // Core pool size<br>    4,                              // Maximum pool size<br>    30,                             // Keep-alive time<br>    TimeUnit.SECONDS,<br>    new ArrayBlockingQueue&lt;&gt;(2),    // Queue capacity<br>    new ThreadPoolExecutor.AbortPolicy()<br>);</pre><p>Let’s break down what each parameter means.</p><p><strong>corePoolSize — The regular workers</strong></p><p>Here, the core pool size is 2.</p><p>As tasks arrive, the executor creates workers until it reaches the core size. By default, these workers are created as needed rather than all being started immediately.</p><p><strong>maximumPoolSize — The upper limit</strong></p><p>The maximum pool size is 4.</p><p>This means the executor can grow to four worker threads when the queueing rules require it.</p><p>But here’s an important detail: <strong>the executor generally queues tasks before creating workers beyond the core size.</strong></p><p><strong>workQueue — The waiting room</strong></p><p>We’re using new ArrayBlockingQueue&lt;&gt;(2), which can hold two waiting tasks.</p><p>If both core workers are busy, additional tasks can wait in this queue.</p><p>A bounded queue helps limit the amount of pending work that accumulates in memory.</p><p><strong>keepAliveTime — Cleaning up after a traffic spike</strong></p><p>We set the keep-alive time to 30 seconds.</p><p>If the pool temporarily grows beyond its core size, excess idle workers can terminate after the configured idle period. Core workers generally remain available unless core-thread timeout is enabled.</p><p><strong>RejectedExecutionHandler — What happens when the pool is full?</strong></p><p>Our configuration uses AbortPolicy.</p><p>When the queue is full, all workers are busy, and the pool cannot grow any further, the executor throws a RejectedExecutionException for the rejected submission.</p><p>That’s not necessarily a bad thing. Sometimes, rejecting additional work is safer than accepting more than the application can handle.</p><h3>4. What Actually Happens When the Pool Fills Up?</h3><p>Let’s make this concrete.</p><p>Our executor has:</p><ul><li><strong>2 core workers</strong></li><li><strong>4 maximum workers</strong></li><li><strong>A queue capacity of 2 tasks</strong></li></ul><p>We’ll submit seven tasks. Each task will take two seconds to simulate work.</p><pre>import java.util.concurrent.ArrayBlockingQueue;<br>import java.util.concurrent.RejectedExecutionException;<br>import java.util.concurrent.ThreadPoolExecutor;<br>import java.util.concurrent.TimeUnit;</pre><pre>public class ThreadPoolCapacityDemo {</pre><pre>    public static void main(String[] args) {</pre><pre>        ThreadPoolExecutor executor = new ThreadPoolExecutor(<br>            2,<br>            4,<br>            30,<br>            TimeUnit.SECONDS,<br>            new ArrayBlockingQueue&lt;&gt;(2),<br>            new ThreadPoolExecutor.AbortPolicy()<br>        );</pre><pre>        try {<br>            for (int i = 1; i &lt;= 7; i++) {<br>                int taskId = i;</pre><pre>                try {<br>                    executor.execute(() -&gt; {<br>                        System.out.println(<br>                            &quot;Task &quot; + taskId + &quot; started on &quot;<br>                            + Thread.currentThread().getName()<br>                        );</pre><pre>                        try {<br>                            Thread.sleep(2000);<br>                        } catch (InterruptedException e) {<br>                            Thread.currentThread().interrupt();<br>                            System.out.println(<br>                                &quot;Task &quot; + taskId + &quot; interrupted&quot;<br>                            );<br>                        }<br>                    });</pre><pre>                } catch (RejectedExecutionException e) {<br>                    System.out.println(<br>                        &quot;Task &quot; + taskId + &quot; was rejected&quot;<br>                    );<br>                }<br>            }<br>        } finally {<br>            executor.shutdown();</pre><pre>            try {<br>                if (!executor.awaitTermination(<br>                        10, TimeUnit.SECONDS)) {<br>                    executor.shutdownNow();<br>                }<br>            } catch (InterruptedException e) {<br>                executor.shutdownNow();<br>                Thread.currentThread().interrupt();<br>            }<br>        }<br>    }<br>}</pre><p>Let’s walk through what happens when the tasks arrive quickly, before any of the two-second tasks finishes.</p><p><strong>Tasks 1 and 2: The core workers</strong></p><p>The executor creates two workers to execute the first two tasks.</p><p>&lt;text&gt;</p><p>&lt;/text&gt;</p><pre>Worker 1 → Task 1<br>Worker 2 → Task 2</pre><p><strong>Tasks 3 and 4: The queue</strong></p><p>Both core workers are busy, so the next two tasks enter the queue.</p><pre>Worker 1 → Task 1<br>Worker 2 → Task 2</pre><pre>Queue → Task 3, Task 4</pre><p>The queue is now full.</p><p><strong>Tasks 5 and 6: The pool grows</strong></p><p>The queue cannot accept more work. The executor can now create additional workers, up to the maximum of four.</p><pre>Worker 1 → Task 1<br>Worker 2 → Task 2<br>Worker 3 → Task 5<br>Worker 4 → Task 6</pre><pre>Queue → Task 3, Task 4</pre><p><strong>Task 7: Rejected</strong></p><p>All four workers are busy, and both queue slots are occupied.</p><p>There is nowhere to put Task 7, so AbortPolicy rejects it.</p><pre>Running tasks: 4<br>Queued tasks:  2<br>New task:      REJECTED</pre><p>The exact order of execution can vary, but the executor’s admission rules are what matter.</p><p><strong>The rule to remember is: core workers → queue → extra workers → rejection.</strong></p><p>The executor doesn’t simply create more threads whenever it gets busy. It follows a defined order.</p><h3>5. The Configuration Mistake That Can Hurt Your Application</h3><p>Now that we understand the execution order, consider this configuration:</p><pre>new ThreadPoolExecutor(<br>    4,<br>    50,<br>    60,<br>    TimeUnit.SECONDS,<br>    new LinkedBlockingQueue&lt;&gt;()<br>);</pre><p>At first glance, this looks like a pool that can grow to 50 threads when traffic increases.</p><p>But it probably won’t behave the way you expect.</p><p>The queue is effectively unbounded, so it can continue accepting tasks after the four core workers become busy. Because the queue doesn’t fill up, the executor generally has no reason to create additional workers beyond the core size.</p><p>Your application may end up with four workers processing tasks while a huge number of tasks wait in memory.</p><p>If that continues, memory pressure and latency can increase dramatically, potentially leading to an OutOfMemoryError.</p><p><strong>A large maximum pool size does not protect you from an unbounded queue.</strong></p><p>The queue and worker limits must be designed together.</p><h3>6. execute() vs. submit(): Don&#39;t Lose Track of Failures</h3><p>There are two common ways to submit tasks to an executor.</p><p>Use execute() when you want to run a task without receiving a Future:</p><pre>executor.execute(() -&gt; {<br>    System.out.println(&quot;Refreshing product cache&quot;);<br>});</pre><p>Use submit() when you want a Future that can expose a result or the outcome of the task:</p><pre>Future&lt;Integer&gt; future = executor.submit(() -&gt; {<br>    return 20 + 22;<br>});</pre><p>You can retrieve its result using:</p><pre>try {<br>    int result = future.get();<br>    System.out.println(result);<br>} catch (InterruptedException e) {<br>    Thread.currentThread().interrupt();<br>} catch (ExecutionException e) {<br>    System.err.println(&quot;Task failed: &quot; + e.getCause());<br>}</pre><p>The result is 42.</p><p>But notice this line:</p><pre>future.get();</pre><p>It blocks the calling thread until the task finishes if the result isn’t ready.</p><p>There’s another subtle difference.</p><p>If a task submitted using submit() throws an exception, the exception is captured by its Future. Calling get() exposes the failure through an ExecutionException.</p><p>If you ignore the Future, the failure may go unnoticed by the calling code.</p><p>This is especially important for background tasks, where the original request may already have returned a response.</p><h3>7. What Should Happen When Tasks Are Rejected?</h3><p>When the pool reaches capacity, the rejection policy decides what happens next.</p><p>Java provides four built-in policies.</p><p><strong>AbortPolicy</strong></p><p>Throws a RejectedExecutionException. This makes rejection explicit, allowing the application to handle it—for example, by returning an appropriate error when an HTTP request cannot be accepted for processing.</p><p><strong>CallerRunsPolicy</strong></p><p>Runs the task on the thread that submitted it, unless the executor has shut down. This can slow down the producer, creating a form of backpressure, but it can also block a request-handling thread.</p><p><strong>DiscardPolicy</strong></p><p>Silently discards the rejected task. This is dangerous if the work matters.</p><p><strong>DiscardOldestPolicy</strong></p><p>Removes the oldest queued task and retries the submission, subject to the executor’s state.</p><p>There is no universally correct policy.</p><p>Losing a best-effort cache refresh may be acceptable. Losing a payment-related task is a different story.</p><p>The right policy depends on the business requirements and the consequences of losing or delaying work.</p><h3>8. Where Does ThreadPoolExecutor Fit in Real Projects?</h3><p>Thread pools are useful in many backend workloads.</p><p>In an e-commerce application, a dedicated executor might handle suitable background tasks such as sending order-confirmation emails.</p><p>A report-generation service might limit how many PDFs it generates concurrently.</p><p>An image-processing service might control how many image transformations happen at once.</p><p>A backend that calls several independent downstream APIs might use concurrency to reduce waiting time.</p><p>In Spring Boot, ThreadPoolTaskExecutor is commonly used with @Async to execute suitable service methods asynchronously.</p><p>However, there’s an important limitation: <strong>a thread pool is an in-memory execution mechanism, not a durable job queue.</strong></p><p>If your server crashes, queued tasks can be lost. For critical workflows, you may need durable messaging, retries, idempotency, and monitoring.</p><h3>9. How Many Threads Should You Use?</h3><p>There isn’t a single number that works for every application.</p><p>The answer depends on the type of work being performed.</p><p><strong>CPU-bound tasks</strong> include heavy calculations, encryption, and image processing. A starting point is to consider the number of available processors. Creating too many runnable threads can increase context switching without improving throughput.</p><p><strong>I/O-bound tasks</strong> include database queries, network requests, and file operations. More concurrency may help workers make progress while others wait, but excessive concurrency can overload databases, connection pools, or external APIs.</p><p>Don’t simply copy numbers from a tutorial.</p><p>Start with reasonable limits, run load tests, and monitor active worker count, queue depth, task execution time, rejected tasks, CPU usage, and memory consumption.</p><p>These measurements will tell you whether the pool needs adjustment or whether the real bottleneck lies somewhere else.</p><h3>Final Thoughts</h3><p>The most useful thing about ThreadPoolExecutor isn&#39;t just knowing its constructor or memorizing a few methods.</p><p>It’s understanding the problems it helps us control.</p><p><strong>How many tasks can run at once?</strong></p><p><strong>How much work can wait?</strong></p><p><strong>When should the pool grow?</strong></p><p><strong>What happens when the system cannot accept more work?</strong></p><p>Once you understand those questions, thread pools stop feeling like a complicated Java API and start making sense as a practical tool for building reliable backend systems.</p><p>Writing code that works during local testing is one thing. Understanding how it behaves under load is another.</p><p>And that is where learning Java concurrency becomes valuable.</p><p><em>Further reading: </em><a href="https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/util/concurrent/ThreadPoolExecutor.html"><em>Java ThreadPoolExecutor — Official Documentation</em></a><em> and </em><a href="https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/util/concurrent/ExecutorService.html"><em>ExecutorService — Official Documentation</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f09c05780f2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Error, One Fix: @ControllerAdvice vs @RestControllerAdvice in Spring Boot]]></title>
            <link>https://medium.com/@unknown0149/one-error-one-fix-controlleradvice-vs-restcontrolleradvice-in-spring-boot-9abb35d19ab5?source=rss-6a30a2fdc261------2</link>
            <guid isPermaLink="false">https://medium.com/p/9abb35d19ab5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[restcontroller]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Aryan Chauhan]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 13:34:10 GMT</pubDate>
            <atom:updated>2026-10-28T13:34:10.551Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ever wondered how Spring Boot handles errors without writing the same code in every controller?</h3><p>Let’s understand it with a simple example.</p><h3>The problem</h3><p>Imagine you’re building a college management app. A user requests a student who doesn’t exist.</p><p>Your API throws an error:</p><pre>Student not found!</pre><p>If 50 APIs can fail, writing error-handling code in all 50 places would be repetitive.</p><p><strong>Spring Boot lets us handle errors in one central place.</strong></p><p>That’s where @ControllerAdvice and @RestControllerAdvice come in.</p><h3>1. @ControllerAdvice: Handling errors for webpages</h3><p>Suppose your Spring Boot application renders HTML pages. When something goes wrong, you want to display an error page.</p><p>Here’s an example:</p><pre>import org.springframework.stereotype.Controller;<br>import org.springframework.ui.Model;<br>import org.springframework.web.bind.annotation.ControllerAdvice;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.GetMapping;</pre><pre>@Controller<br>class PageController {</pre><pre>    @GetMapping(&quot;/page&quot;)<br>    public String page() {<br>        throw new IllegalStateException(&quot;Page failed&quot;);<br>    }<br>}</pre><pre>@ControllerAdvice<br>class PageExceptionHandler {</pre><pre>    @ExceptionHandler(IllegalStateException.class)<br>    public String handleError(<br>            IllegalStateException ex, Model model) {</pre><pre>        model.addAttribute(&quot;message&quot;, ex.getMessage());</pre><pre>        return &quot;error&quot;;<br>    }<br>}</pre><p>What’s happening here?</p><ul><li>/page throws an exception.</li><li>@ControllerAdvice lets Spring handle that exception centrally.</li><li>@ExceptionHandler selects the method that handles it.</li><li>return &quot;error&quot; tells Spring to render a view named error.</li></ul><p>For this example to work at runtime, add the Spring Boot Thymeleaf starter and create this file:</p><p><strong>src/main/resources/templates/error.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Error&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Something went wrong!&lt;/h1&gt;<br>    &lt;p th:text=&quot;${message}&quot;&gt;&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now Spring can render an error webpage displaying the exception message.</p><h3>2. @RestControllerAdvice: Handling errors for REST APIs</h3><p>Now imagine your backend serves a React frontend.</p><p>Instead of returning an HTML page, you want to send an error as JSON.</p><p>Here’s a complete example with the required imports:</p><pre>import java.util.Map;</pre><pre>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PathVariable;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br>import org.springframework.web.bind.annotation.RestControllerAdvice;</pre><pre>@RestController<br>@RequestMapping(&quot;/students&quot;)<br>class StudentController {</pre><pre>    @GetMapping(&quot;/{id}&quot;)<br>    public Map&lt;String, Object&gt; getStudent(<br>            @PathVariable int id) {</pre><pre>        if (id != 1) {<br>            throw new StudentNotFoundException(<br>                &quot;Student not found&quot;<br>            );<br>        }</pre><pre>        return Map.of(&quot;id&quot;, 1, &quot;name&quot;, &quot;Aryan&quot;);<br>    }<br>}</pre><pre>class StudentNotFoundException extends RuntimeException {</pre><pre>    public StudentNotFoundException(String message) {<br>        super(message);<br>    }<br>}</pre><pre>@RestControllerAdvice<br>class ApiExceptionHandler {</pre><pre>    @ExceptionHandler(StudentNotFoundException.class)<br>    public ResponseEntity&lt;Map&lt;String, String&gt;&gt; handleError(<br>            StudentNotFoundException ex) {</pre><pre>        Map&lt;String, String&gt; error = Map.of(<br>            &quot;error&quot;, ex.getMessage()<br>        );</pre><pre>        return ResponseEntity<br>                .status(HttpStatus.NOT_FOUND)<br>                .body(error);<br>    }<br>}</pre><p>This example assumes a standard Spring Boot web project and Java 9 or later.</p><p>If you request /students/1, you receive student data.</p><p>If you request /students/20, you receive:</p><p><strong>HTTP status:</strong> 404 Not Found</p><pre>{<br>  &quot;error&quot;: &quot;Student not found&quot;<br>}</pre><p>Your React frontend can read this JSON and display an appropriate error message.</p><h3>3. What’s the actual difference?</h3><p>Here’s the easiest way to remember it:</p><ul><li>@ControllerAdvice provides shared controller behavior. Its handler methods use normal MVC response handling by default, so a returned string can represent a view name.</li><li>@RestControllerAdvice provides shared controller behavior with response-body handling enabled by default, making it convenient for JSON APIs.</li></ul><p>Here’s the interesting part:</p><pre>@ControllerAdvice<br>@ResponseBody</pre><p>These annotations together provide the core behavior of @RestControllerAdvice.</p><p>@ResponseBody tells Spring to write the returned value into the HTTP response body instead of treating it as a view name.</p><p><strong>That’s the main difference.</strong></p><h3>4. Which one should you use?</h3><p>Building a traditional Spring MVC website that renders HTML pages? @ControllerAdvice is a natural choice.</p><p>Building a Spring Boot REST API for React or a mobile app? @RestControllerAdvice is usually more convenient.</p><p>Both can handle exceptions centrally. And @ControllerAdvice can also return JSON when response-body handling is enabled appropriately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9xmuEaOX3nkeuYJPoz6ow.png" /></figure><h3>Remember this</h3><p>You don’t need to handle every error separately in every controller.</p><p><strong>Write your exception-handling logic once and let Spring Boot handle it centrally.</strong></p><p>That’s the idea behind global exception handling.</p><p>#Java #SpringBoot #BackendDevelopment #RESTAPI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9abb35d19ab5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From a Long Spring Boot Stack Trace to Clean API Error Responses.]]></title>
            <link>https://medium.com/@unknown0149/from-a-long-spring-boot-stack-trace-to-clean-api-error-responses-42850d41ab75?source=rss-6a30a2fdc261------2</link>
            <guid isPermaLink="false">https://medium.com/p/42850d41ab75</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Aryan Chauhan]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 04:53:02 GMT</pubDate>
            <atom:updated>2026-10-27T04:53:02.585Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding </em><em>@Valid, </em><em>@RestControllerAdvice, and </em><em>@ExceptionHandler by building a global validation error handler.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEa1UEWhAc1G8Anrak7MEA.png" /></figure><h3>The problem that started it</h3><p>While learning Spring Boot and building a Patient Service REST API, I ran into a problem that many backend developers eventually encounter: validation errors.</p><p>I sent a POST request to /patients using Postman. The request contained patient details, but one of the fields failed validation.</p><p>Spring Boot returned a 400 Bad Request, along with a detailed error response containing the exception type, stack trace, rejected value, and validation message.</p><p>The request had failed for a valid reason. The problem was that the response was difficult to read when I only wanted to understand which field was wrong and how to correct it.</p><p>That led me to explore a few important questions:</p><ul><li>How does Spring Boot detect invalid request data?</li><li>What exactly happens when @Valid fails?</li><li>How can I handle validation errors centrally instead of writing the same logic in every controller?</li><li>How can I return a clean, consistent JSON response?</li></ul><p>The answer involves three concepts: DTO validation, exception handling, and HTTP responses.</p><h3>1. Understanding how request validation works</h3><p>Consider a simplified patient request DTO:</p><pre>import jakarta.validation.constraints.Email;<br>import jakarta.validation.constraints.NotBlank;<br>import jakarta.validation.constraints.Size;</pre><pre>public class PatientRequestDTO {</pre><pre>    @NotBlank(message = &quot;Name is required&quot;)<br>    @Size(<br>        max = 100,<br>        message = &quot;Name cannot exceed 100 characters&quot;<br>    )<br>    private String name;</pre><pre>    @NotBlank(message = &quot;Email is required&quot;)<br>    @Email(message = &quot;Please provide a valid email address&quot;)<br>    private String email;</pre><pre>    // Getters and setters<br>}</pre><p>The annotations define the rules that incoming data must satisfy.</p><ul><li>@NotBlank rejects null, empty, and whitespace-only strings.</li><li>@Size(max = 100) limits the length of the name.</li><li>@Email checks whether the value satisfies the email validator.</li></ul><p>One small but important lesson I learned while debugging: @Min and @Max are numeric constraints. They are not the right way to limit the length of a String. For that, use @Size.</p><p>These rules describe what valid data should look like. But how does Spring apply them to an incoming HTTP request?</p><h3>2. What happens when a POST request arrives?</h3><p>A controller method can look like this:</p><pre>@PostMapping<br>public ResponseEntity&lt;PatientResponseDTO&gt; createPatient(<br>        @Valid @RequestBody PatientRequestDTO request) {</pre><pre>    PatientResponseDTO response =<br>            patientService.createPatient(request);</pre><pre>    return ResponseEntity<br>            .status(HttpStatus.CREATED)<br>            .body(response);<br>}</pre><p>Two annotations are doing different jobs here.</p><h3>@RequestBody</h3><p>This tells Spring MVC to read the HTTP request body and deserialize the incoming JSON into a PatientRequestDTO object.</p><p>For example:</p><pre>{<br>  &quot;name&quot;: &quot;Rahul Sharma&quot;,<br>  &quot;email&quot;: &quot;not-an-email&quot;<br>}</pre><p>Spring maps the JSON values to the corresponding DTO properties.</p><h3>@Valid</h3><p>This triggers validation of the DTO using its configured validation constraints.</p><p>In this example, the email value fails the @Email constraint.</p><p>For an ordinary @Valid @RequestBody validation failure, Spring MVC raises a MethodArgumentNotValidException and normally returns HTTP 400 Bad Request if the exception is not handled differently.</p><p>The controller method body does not proceed to create the patient when this argument validation fails.</p><p>This is the first important distinction:</p><p><strong>@RequestBody maps the JSON. </strong><strong>@Valid checks the resulting object.</strong></p><h3>3. Introducing global exception handling</h3><p>Instead of handling validation failures separately in every controller, Spring provides centralized exception handling through @ControllerAdvice and @RestControllerAdvice.</p><p>For a REST API, I can use @RestControllerAdvice because it combines controller-advice behavior with response-body serialization.</p><p>Here is a simple global validation handler:</p><pre>import java.util.LinkedHashMap;<br>import java.util.Map;</pre><pre>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.MethodArgumentNotValidException;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.RestControllerAdvice;</pre><pre>@RestControllerAdvice<br>public class GlobalExceptionHandler {</pre><pre>    @ExceptionHandler(MethodArgumentNotValidException.class)<br>    public ResponseEntity&lt;Map&lt;String, String&gt;&gt;<br>            handleValidationException(<br>                    MethodArgumentNotValidException ex) {</pre><pre>        Map&lt;String, String&gt; errors = new LinkedHashMap&lt;&gt;();</pre><pre>        ex.getBindingResult()<br>                .getFieldErrors()<br>                .forEach(error -&gt;<br>                    errors.putIfAbsent(<br>                        error.getField(),<br>                        error.getDefaultMessage()<br>                    )<br>                );</pre><pre>        return ResponseEntity<br>                .badRequest()<br>                .body(errors);<br>    }<br>}</pre><p>Let’s understand why this works.</p><h3>@RestControllerAdvice</h3><p>This allows the exception-handling method to apply across controllers, rather than requiring the same handler in every controller class.</p><h3>@ExceptionHandler</h3><p>This tells Spring which exception type the method handles.</p><p>Here, the handler targets MethodArgumentNotValidException, which commonly arises from validation of a @Valid @RequestBody DTO.</p><p>It does not automatically handle every possible application error.</p><h3>ex.getBindingResult().getFieldErrors()</h3><p>The exception contains information about the validation failures.</p><p>getFieldErrors() returns the field-level errors, including details such as the field name and the associated validation message.</p><p>For example, one error may identify the email field and contain the message Please provide a valid email address.</p><h3>forEach() and the lambda expression</h3><p>This part is worth understanding:</p><pre>.forEach(error -&gt;<br>    errors.putIfAbsent(<br>        error.getField(),<br>        error.getDefaultMessage()<br>    )<br>);</pre><p>forEach() iterates over the list of field errors.</p><p>The lambda expression error -&gt; ... tells Java what to do with each error.</p><p>For every field error:</p><ul><li>error.getField() retrieves the field name.</li><li>error.getDefaultMessage() retrieves the configured validation message.</li><li>errors.putIfAbsent() stores the message against that field if no message has been stored for it yet.</li></ul><p>I could also write this using a traditional for loop. The lambda is a shorter way of expressing the same operation.</p><p>I used LinkedHashMap to retain insertion order, which makes the response easier to read. This is useful for presentation, although clients should not depend on JSON property order.</p><p>One limitation is that a Map&lt;String, String&gt; stores only one message per field. If I want to return every validation message for a field that violates several constraints, I would use a structure such as Map&lt;String, List&lt;String&gt;&gt; instead.</p><h3>4. What does the client receive now?</h3><p>For the invalid request:</p><pre>{<br>  &quot;name&quot;: &quot;Rahul Sharma&quot;,<br>  &quot;email&quot;: &quot;not-an-email&quot;<br>}</pre><p>The handler can return a response like this:</p><pre>{<br>  &quot;email&quot;: &quot;Please provide a valid email address&quot;<br>}</pre><p>The HTTP status remains:</p><pre>400 Bad Request</pre><p>The important improvement is not that the invalid request is suddenly accepted. It is that the API communicates the validation failure in a concise, predictable format.</p><p>A frontend can use the field name to associate the error with the appropriate input. A developer testing the endpoint in Postman can quickly identify what needs to change.</p><p>The exact response depends on the validation constraints that fail and on how the handler is implemented.</p><h3>5. Why centralize exception handling?</h3><p>Imagine an application with patient, doctor, appointment, and billing controllers.</p><p>Without centralized handling, each controller might end up implementing similar error-response logic. Over time, those responses can become inconsistent.</p><p>A global handler provides a common place to define how selected exceptions are represented in HTTP responses.</p><p>The benefits include:</p><ul><li><strong>Consistency:</strong> Multiple controllers can follow the same response format.</li><li><strong>Maintainability:</strong> Shared handling logic lives in one place.</li><li><strong>Readability:</strong> Controllers can focus on request handling and application logic.</li><li><strong>Better API usability:</strong> Clients receive useful error information without having to interpret a long stack trace.</li></ul><p>There is also an important security consideration. Detailed exception traces are useful during development, but they should not be exposed indiscriminately to public API clients. Internal diagnostics belong in server-side logs, while client responses should reveal only the details appropriate for that API.</p><h3>6. A few things this handler does not solve</h3><p>A global validation handler is a useful starting point, not a complete error-handling strategy.</p><p><strong>Malformed JSON is a different problem.</strong> If the request body contains invalid JSON syntax or cannot be deserialized into the expected Java types, Spring may raise HttpMessageNotReadableException instead. That requires separate handling if a custom response is desired.</p><p><strong>Business errors need their own treatment.</strong> For example, attempting to create a patient with an email that already exists is a business or persistence rule, not necessarily a DTO validation error.</p><p><strong>Multiple validation messages require a deliberate response design.</strong> The simple map in this example preserves only one message per field. More complete APIs can return a list of messages or adopt a standardized error structure.</p><p>Understanding which exception occurred is just as important as writing the handler itself.</p><h3>7. What I took away from this</h3><p>The biggest lesson for me was that request validation and exception handling are two separate stages.</p><p>Validation identifies invalid input. Spring raises an exception when the relevant validation fails. The global handler then decides how to present that failure to the API client.</p><p>I also learned to read an error response methodically: look at the HTTP status, identify the failing field, inspect the rejected value, and find the constraint that failed before changing the code.</p><p>That approach helped me understand Spring Boot beyond simply getting an endpoint to work.</p><p>As I continue developing backend applications, I want to focus on not only handling successful requests, but also making failures clear, consistent, and easier to debug.</p><p><strong>A useful API is not just one that works when everything goes right. It should also communicate clearly when something goes wrong.</strong></p><h3>References</h3><ul><li><a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/requestbody.html">Spring Framework documentation: </a><a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/requestbody.html">@RequestBody and validation</a></li><li><a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-advice.html">Spring Framework documentation: Controller Advic</a>e</li><li><a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-exceptionhandler.html">Spring Framework documentation: Exception handling</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42850d41ab75" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>