<?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 Debmalya Pan on Medium]]></title>
        <description><![CDATA[Stories by Debmalya Pan on Medium]]></description>
        <link>https://medium.com/@debmalyapan98?source=rss-e25cd5dd254b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_uybYK_s0Wg87MzxNmzGjQ.jpeg</url>
            <title>Stories by Debmalya Pan on Medium</title>
            <link>https://medium.com/@debmalyapan98?source=rss-e25cd5dd254b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:35:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@debmalyapan98/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[Building a Service Desk Chatbot using AI and MCP]]></title>
            <link>https://medium.com/@debmalyapan98/building-a-service-desk-chatbot-using-ai-and-mcp-9b68766a4ea7?source=rss-e25cd5dd254b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b68766a4ea7</guid>
            <category><![CDATA[ai-chatbot]]></category>
            <category><![CDATA[ai-tool-calling]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[google-gemini]]></category>
            <dc:creator><![CDATA[Debmalya Pan]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 16:45:51 GMT</pubDate>
            <atom:updated>2026-03-16T17:42:11.964Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey folks, I thought of writing yet another article to demonstrate the concepts of MCP and how we can scale a chatbot to leverage multiple tools hosted over the web.</p><p>Before jumping to the problem, lets understand what MCP is.</p><h4>MCP Terminologies:</h4><p><strong>MCP:</strong> Model Context Protocol (MCP) is a protocol (built by Anthropic) that standardizes a way for LLM models to connect to different data sources or servers hosting the tools. In simple words, it is AI-specific and built on top of protocols like HTTP, thus making it more efficient, reliable and easy to use.</p><p><strong>MCP Host</strong>: The AI application (e.g chatbot app) . It uses the LLM model, manages the conversation and decides when to invoke tools based on LLM’s feedback.</p><p><strong>MCP Client (or Adapter)</strong>: An adapter that handles tool invocation requests to the MCP Server. It is usually coded in the MCP host, though you may choose to build a separate library and add it as a dependency.</p><p><strong>MCP Server</strong>: The application responsible for exposing its capabilities as tools (similar to APIs).</p><h4>MCP Transport Types:</h4><p><strong>i. Standard Input/Output (stdio) </strong>: Used when the host, client &amp; server are running locally. It doesnt need network protocol configuration and operates through pipes.</p><p><strong>ii. Server Sent Events (SSE) </strong>: <strong>Deprecated</strong>, but still used for backward compatibility. It uses HTTP POST for client requests and SSE streams for server responses. Latency is higher compared to Streamable HTTP.</p><p><strong>iii. Streamable HTTP </strong>: Provides a unified interface with flexible bidirectional streaming.</p><p>Please read <a href="https://brightdata.com/blog/ai/sse-vs-streamable-http">https://brightdata.com/blog/ai/sse-vs-streamable-http</a> to understand the pros and cons in details.</p><p>In this demonstration, we’ll focus on remote invocation rather than using STDIO.</p><h4><strong>Problem Statement:</strong></h4><p>We need to build a chatbot that helps service desk executives:</p><p>a. Create tickets<br>b. Get ticket status<br>c. Update ticket status<br>d. Update ticket description<br>e. Add comment(s) to a ticket</p><h4>Requirements:</h4><p>Based on the problem statement, the following features are needed:</p><ol><li>Java (v24), Spring Boot (v3.5.9), Spring AI BOM (v1.1.2)</li><li>Tool Calling: Gemini as the LLM model (spring-ai-starter-model-google-genai dependency in MCP client app)</li><li>H2 DB: In-memory DB for LLM chat memory (added in MCP client app)</li><li>MCP Client: spring-ai-starter-mcp-client dependency (added in MCP client app)</li><li>REST API: spring-boot-starter-web dependency (added in MCP client app)</li><li>MCP Server: spring-ai-starter-mcp-server-webmvc dependency (added in MCP server app)</li><li>JDBC/JPA: spring-boot-starter-data-jpa dependency (added in MCP server app) for CRUD operations on tickets.</li></ol><h4>How to approach the problem?</h4><p><strong>MCP Client:</strong></p><ol><li>Exposes an API (/chat) that accepts client requests and passes them to the LLM model.</li><li>Maintains chat conversations for each user in its chat memory.</li><li>On startup, discovers all tools exposed by MCP servers based on base URLs provided in application.properties.</li></ol><p><strong>MCP Server:</strong></p><ol><li>Contains the business logic (service and repository layers).</li><li>Expose these functionalities as tools.</li></ol><h3>Code Walkthrough:</h3><h4><strong>MCP Client:</strong></h4><ol><li>Controller Layer :</li></ol><pre>@RestController<br>@RequestMapping(&quot;api&quot;)<br>@AllArgsConstructor(onConstructor = @__(@Autowired))<br>public class ChatController {<br><br>    private final ChatClient chatClient;<br><br>    @GetMapping(&quot;/chat&quot;)<br>    public ResponseEntity&lt;String&gt; helpDesk(@RequestHeader(&quot;userId&quot;) String userId,<br>                                           @RequestParam(&quot;message&quot;) String message) {<br>        String answer = chatClient.prompt()<br>                .advisors(a -&gt; a.param(CONVERSATION_ID, userId))<br>                .user(message)<br>                .call().content();<br>        return ResponseEntity.ok(answer);<br>    }<br>}</pre><p>2. Advisor Configuration:</p><pre>@Configuration<br>public class AdvisorConfig {<br><br>    @Bean<br>    public SimpleLoggerAdvisor loggerAdvisor(){<br>        return new SimpleLoggerAdvisor();<br>    }<br><br>    @Bean<br>    public MessageChatMemoryAdvisor memoryAdvisor(ChatMemory chatMemory) {<br>        return MessageChatMemoryAdvisor.builder(chatMemory).build();<br>    }<br><br><br>    @Bean<br>    ChatMemory chatMemory(JdbcChatMemoryRepository jdbcChatMemoryRepository) {<br>        return MessageWindowChatMemory.builder().maxMessages(10)                //default is 20<br>                .chatMemoryRepository(jdbcChatMemoryRepository).build();<br>    }<br>}</pre><p>3. Chat client configuration:</p><pre>@Configuration<br>public class ChatClientConfig {<br><br>    @Bean<br>    public ChatClient geminiChatClient(GoogleGenAiChatModel chatModel,<br>                                       MessageChatMemoryAdvisor memoryAdvisor,<br>                                       SimpleLoggerAdvisor geminiLoggerAdvisor,<br>                                       ToolCallbackProvider toolCallbackProvider) {<br>        return ChatClient.builder(chatModel)<br>                .defaultAdvisors(List.of(geminiLoggerAdvisor, memoryAdvisor))<br>                .defaultToolCallbacks(toolCallbackProvider)<br>                .build();<br>    }</pre><p><strong>Added bonus:</strong> You can register a listener to detect tool changes. This helps when new tools are deployed on the MCP server, allowing the MCP client to discover them without cascading deployments.</p><pre>@Bean<br>public McpSyncClientCustomizer mcpSyncClientCustomizer() {<br>    return (name, mcpClientSpec) -&gt; {<br>        mcpClientSpec.toolsChangeConsumer(tools -&gt; {<br>            log.info(&quot;Detected tools changes.&quot;);<br>        });<br>    };<br>}</pre><p>4. The application.properties would contain the base urls of the MCP servers.<br><em>Property:</em><br><em>If you’re using streamable HTTP</em>: spring.ai.mcp.client.streamable-http.connections.server.url<br><em>If you’re using SSE</em>: spring.ai.mcp.client.sse.connections.server.url</p><p><strong>Added Bonus #2 : </strong>You can add Spring Security (OAuth2) to implement authorization to the APIs as well.</p><h4><strong>MCP Server:</strong></h4><ol><li>The <strong>Service</strong> and <strong>Repository</strong> layers can be implemented by any Java backend developer, so I won’t go into a deep dive here. The key step is to expose the service methods as tools.</li></ol><pre>@Component<br>@RequiredArgsConstructor<br>public class HelpDeskTools {<br>    private final HelpDeskTicketService service;<br><br>    @Tool(name = &quot;createTicket&quot;, description = &quot;Create the Support Ticket&quot;)<br>    String createTicket(@ToolParam(description = &quot;Details to create a Support ticket&quot;)<br>                        TicketRequest ticketRequest) {<br>        LOGGER.info(&quot;Creating support ticket for user: {} with details: {}&quot;, ticketRequest.userId(), ticketRequest.issue());<br>        HelpDeskTicket savedTicket = service.createTicket(ticketRequest);<br>        LOGGER.info(&quot;Ticket created successfully. Ticket ID: {}, userId: {}&quot;, savedTicket.getId(), savedTicket.getUserId());<br>        return &quot;Ticket #&quot; + savedTicket.getId() + &quot; created successfully for user &quot; + savedTicket.getUserId();<br>    }<br><br>    @Tool(name = &quot;getTicketStatus&quot;, description = &quot;Fetch the status of the tickets based on a given userId&quot;)<br>    List&lt;HelpDeskTicket&gt; getTicketStatus(@ToolParam(description =<br>            &quot;userId to fetch the status of the help desk tickets&quot;) String userId) {<br>        LOGGER.info(&quot;Fetching tickets for user: {}&quot;, userId);<br>        List&lt;HelpDeskTicket&gt; tickets = service.getTicketsByUserId(userId);<br>        LOGGER.info(&quot;Found {} tickets for user: {}&quot;, tickets.size(), userId);<br>        return tickets;<br>    }</pre><p>2. Register these tools as tool callbacks so they can be discovered by the MCP client’s tool provider.</p><pre>@Bean<br>List&lt;ToolCallback&gt; toolCallbacks(HelpDeskTools helpDeskTools) {<br>    return List.of(ToolCallbacks.from(helpDeskTools));<br>}</pre><p>3. In application.properties, mention the MCP transport type as follows:<br>spring.ai.mcp.server.protocol = STATELESS (other options: SSE)</p><p><strong>Added Bonus:<br></strong>For the MCP client listener to work, you need a way to notify the client of tool updates. For example, if the MCP server starts providing hotel booking capabilities, you can notify the client as follows:</p><pre>List&lt;McpServerFeatures.SyncToolSpecification&gt; newTools = McpToolUtils<br>        .toSyncToolSpecifications(ToolCallbacks.from(new HotelBookingService()));<br><br>for (McpServerFeatures.SyncToolSpecification newTool : newTools) {<br>    logger.info(&quot;Add new tool: &quot; + newTool);<br>    mcpSyncServer.addTool(newTool);<br>    mcpSyncServer.notifyToolsListChanged();<br>}</pre><h4>Conclusion</h4><p>This setup demonstrates how to build a service desk chatbot in a client–server architecture using the MCP protocol, Spring Boot, Gemini for LLM capabilities, and H2 for chat memory.</p><p><em>MCP References:</em></p><p><strong>Official Documentation:</strong> <a href="https://modelcontextprotocol.io/docs/learn">https://modelcontextprotocol.io/docs/learn</a><br><strong>GitHub Repository:</strong> <a href="https://github.com/modelcontextprotocol">https://github.com/modelcontextprotocol</a><br><strong>Official Servers:</strong> <a href="https://github.com/modelcontextprotocol/servers">https://github.com/modelcontextprotocol/servers</a><br><strong>MCP Introspector:</strong> Run npx @modelcontextprotocol/inspector for debugging.</p><p>You can find the full implementation here: <a href="https://github.com/debmalyapan53/spring-ai-mcpclient">https://github.com/debmalyapan53/spring-ai-mcpclient</a><br><a href="https://github.com/debmalyapan53/spring-ai-mcpserver">https://github.com/debmalyapan53/spring-ai-mcpserver</a></p><p>#springboot #ai #chatbot #toolcalling #mcp #modelcontextprotocol #java #LLM</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b68766a4ea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Customer Support Chatbot with AI]]></title>
            <link>https://medium.com/@debmalyapan98/building-a-customer-support-chatbot-with-ai-3c146356b79a?source=rss-e25cd5dd254b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c146356b79a</guid>
            <category><![CDATA[ai-tool-calling]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[ai-chatbot]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[google-gemini]]></category>
            <dc:creator><![CDATA[Debmalya Pan]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 16:29:40 GMT</pubDate>
            <atom:updated>2026-03-15T16:34:43.853Z</atom:updated>
            <content:encoded><![CDATA[<p>Last month, I spent a good amount of time learning AI concepts, and I’d like to share some of that knowledge by building an AI agent in Spring Boot.<br>Why Spring Boot and not in Python?<br>Although Python provides an extensive set of libraries and better support for AI development, I wanted to explore Spring-related capabilities first.</p><h3><strong>Problem Statement:</strong></h3><p>We need to build a chatbot that helps customers:</p><ul><li>Retrieve booking details</li><li>Modify bookings (e.g., change the room type)</li><li>Cancel reservations</li><li>Query hotel terms and conditions (T&amp;Cs)</li></ul><h4><strong>Requirements:</strong></h4><p>Based on the problem statement, the following features are needed:<br>1. Java (v24), Spring Boot (v3.5.9), Spring AI BOM (v1.1.2)<br>2. RAG (spring-ai-rag dependency)<br>3. Vector DB for storing the T&amp;Cs: I chose Qdrant. (spring-ai-starter-vector-store-qdrant dependency)<br>4. Tool Calling: I chose Gemini as the LLM model. (spring-ai-starter-model-google-genai &amp; spring-ai-starter-model-google-genai-embedding dependencies)<br>5. H2 DB: Used as an in-memory DB for LLM chat memory</p><h4><strong>How to approach the problem?</strong></h4><p>1. <strong>Expose an API</strong> that accepts user queries and passes them to the LLM model.<br>2. <strong>Load the T&amp;Cs into the Vector DB</strong> during the first run. Splitting the text is required so the entire document doesn’t need to be loaded, making semantic search easier.</p><ul><li>One reason for choosing Qdrant is its ability to visualize data points and perform semantic search using its web interface.</li></ul><p>3. <strong>Implement service and repository layers</strong> to perform CRUD operations.<br>4. <strong>Expose functionalities as tools</strong> (using @Tool and @ToolParam annotations) for the LLM model to fulfill requests.<br>5. <strong>Configure application properties</strong> for H2 DB, Vector DB, booking DB, and the LLM model.</p><h4><strong>Code Walkthrough:</strong></h4><p>1. The main application class has a command-line runner that reads the T&amp;Cs, splits them into chunks, and loads them into the vector store. Chunk size can be configurable, and a feature flag can control whether terms are loaded only when needed.<br>For example, These are booking terms that I’ve taken:</p><pre>These Terms of Service govern your experience with Great Hotel Booking . By booking a hotel, you agree to these terms.<br><br>1. Booking a Stay<br>Book via our website or mobile app.<br>Full payment is required at the time of booking.<br>Ensure the accuracy of your personal information (Name, ID, etc.), as corrections may incur a $25 fee.<br><br>2. Changing Bookings<br>Changes to your booking are allowed up to 24 hours before your check-in date.<br>You can make changes via our website or by contacting our support team.<br>Change fee: $50 for Standard Rooms, $30 for Deluxe Rooms, Free for Suites.<br><br>3. Cancelling Bookings<br>Cancellations can be made up to 48 hours before your check-in date.<br>Cancellation fees: $75 for Standard Rooms, $50 for Deluxe Rooms, $25 for Suites.<br>Refunds will be processed within 7 business days.</pre><pre>@SpringBootApplication<br>public class Application {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(Application.class, args);<br>    }<br><br>    @Bean<br>    public CommandLineRunner commandLineRunner(VectorStore vectorStore,<br>                                               @Value(&quot;classpath:booking-terms.txt&quot;) Resource termsOfServiceDocs,<br>                                               @Value(&quot;${booking-terms.load}&quot;) boolean loadTerms) {<br>        return _ -&gt; {<br>            if (loadTerms) {<br>                List&lt;Document&gt; documents = new TextReader(termsOfServiceDocs).read();<br>                TextSplitter textSplitter = TokenTextSplitter.builder()<br>                        .withChunkSize(50)     //every document will be of 50 token size<br>                        .withMaxNumChunks(100)  //any document should not have a text that exceeds 100 tokens<br>                        .build();<br><br>                List&lt;Document&gt; splitDocuments = textSplitter.split(documents);<br>                vectorStore.add(splitDocuments);<br>            }<br>        };<br>    }<br>}</pre><p>In the Qdrant UI, you can see data points similar to the queried data point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PD1r1LUU0Eq_MutoBkqcuw.png" /></figure><p>2. Next, we need to provide a system prompt to the LLM to set the context for the problem statement.<br>Sharing the prompt here:</p><pre>You are a customer chat support agent of an Hotel Booking named &quot;Great Hotel Booking&quot;.&quot;<br>Respond in a friendly, helpful, and joyful manner.<br>You are interacting with customers through an online chat system.<br>Before providing information about a booking or cancelling a booking, you MUST always<br>get the following information from the user: booking number, customer first name and last name.<br>Check the message history for this information before asking the user.<br>Before changing a booking you MUST ensure it is permitted by the terms.<br>If there is a charge for the change, you MUST ask the user to consent before proceeding.<br>Use the provided functions to fetch booking details, change bookings, and cancel bookings.<br>Use parallel function calling if required.<br>Today is {current_date}.</pre><p>3. Provide the DDLs for table creation for H2 in-memory DB as well as booking DB.<br>4. Create a class called AdvisorsConfig. Advisors are nothing but interceptors. They allow you to:<br>i. Pre-process or post-process prompt data<br>ii. Add custom logging or auditing<br>iii. Inject additional behavior without modifying core logic.<br>iv. Chain multiple behaviors cleanly.<br>v. Stateless and request-scoped</p><p>Users -&gt; ChatClient -&gt; [Advisors] -&gt; LLM -&gt; Response -&gt; [Advisors] -&gt; User</p><p>Here, I’ve used the below advisors:<br><strong>SimpleLoggerAdvisor</strong>: Logs requests and responses.</p><pre>    @Bean<br>    public SimpleLoggerAdvisor loggerAdvisor(){<br>        return new SimpleLoggerAdvisor();<br>    }</pre><p><strong>MessageChatMemoryAdvisor</strong>: Maintains LLM chat memory with a sliding window of 10 messages.</p><pre>    @Bean<br>    ChatMemory chatMemory(JdbcChatMemoryRepository jdbcChatMemoryRepository) {<br>        return MessageWindowChatMemory.builder().maxMessages(10)                //default is 20<br>                .chatMemoryRepository(jdbcChatMemoryRepository).build();<br>    }<br>    @Bean<br>    public MessageChatMemoryAdvisor memoryAdvisor(ChatMemory chatMemory) {<br>        return MessageChatMemoryAdvisor.builder(chatMemory).build();<br>    }</pre><p><strong>RetrievalAugmentationAdvisor</strong>: Connects the Vector DB with the LLM model for RAG.</p><pre>    @Bean<br>    public RetrievalAugmentationAdvisor retrievalAugmentationAdvisor(VectorStore vectorStore) {<br>        return RetrievalAugmentationAdvisor.builder()<br>                .documentRetriever(VectorStoreDocumentRetriever.builder()<br>                        .vectorStore(vectorStore).topK(3).similarityThreshold(0.5).build())<br>                .build();<br>    }</pre><p>5. Now, we need to inject these advisors to the LLM ChatClient. Create a ChatClientConfig class.</p><pre>@Bean(name = &quot;ragChatClientBuilder&quot;)<br>public ChatClient.Builder ragChatClientBuilder(GoogleGenAiChatModel chatModel,<br>                                               MessageChatMemoryAdvisor memoryAdvisor,<br>                                               SimpleLoggerAdvisor loggerAdvisor,<br>                                               RetrievalAugmentationAdvisor retrievalAugmentationAdvisor) {<br>    return ChatClient.builder(chatModel)<br>            .defaultAdvisors(List.of(loggerAdvisor, memoryAdvisor, retrievalAugmentationAdvisor));<br>}</pre><p>6. Next, code the service layer and the repository layer. I trust that this can be done by any Java developer and needs no deep dive.<br>7. Now these functionalities need to be exposed as Tools. Here is how:</p><pre>@Component<br>@AllArgsConstructor<br>public class AgentTools {<br>    private final HotelBookingService hotelBookingService;<br><br>    @Tool(name = &quot;cancelBooking&quot;, description = &quot;cancel a hotel booking based on booking number, first name and last name&quot;)<br>    public void cancelBookingRequest(@ToolParam(description = &quot;details required to cancel a booking&quot;) CancelBookingRequest cancelBookingRequest) {<br>        hotelBookingService.cancelBooking(cancelBookingRequest.bookingNumber(), cancelBookingRequest.firstName(), cancelBookingRequest.lastName());<br>    }<br><br>    @Tool(name = &quot;roomTypeChangeRequest&quot;, description = &quot;change the room type in a booking based on booking number, first name and last name&quot;)<br>    public void roomTypeChangeRequest(@ToolParam(description = &quot;details required to change room type in a booking&quot;) RoomTypeChangeRequest roomTypeChangeRequest) {<br>        hotelBookingService.roomTypeChangeRequest(roomTypeChangeRequest.bookingNumber(), roomTypeChangeRequest.firstName(), roomTypeChangeRequest.lastName(), roomTypeChangeRequest.roomType());<br>    }<br><br>    @Tool(name = &quot;getBookingRequest&quot;, description = &quot;get or retrieve booking details based on booking number, first name and last name&quot;)<br>    public HotelBookingDetails getBooking(@ToolParam(description = &quot;details required to retrieve booking details&quot;) RetrieveBookingRequest retrieveBookingRequest) {<br>        try {<br>            return Mapper.toHotelBookingDetails(hotelBookingService.findBooking(retrieveBookingRequest.bookingNumber(), retrieveBookingRequest.firstName(), retrieveBookingRequest.lastName()));<br>        } catch (Exception e) {<br>            return null;<br>        }<br>    }<br>}</pre><p>The LLM client figures out which tool to invoke based on the tool description as well as the parameters it takes. The LLM model is smart enough to create the POJOs while passing the right arguments and fields required based on the schema provided.</p><p>8. How do we list these tools ?<br>Quite simple.</p><pre>@Bean(name = &quot;tools&quot;)<br>List&lt;ToolCallback&gt; toolCallbacks(AgentTools agentTools) {<br>    return List.of(ToolCallbacks.from(agentTools));<br>}</pre><p>9. An application can have many such tools. How do we pass the right set of tools to the client?<br>There are 2 ways to pass along these tool info:<br>i. You can list a certain set of tools as default tools and configure those while creating the chat client bean itself. <br>ii. You can write code to send a specific set of tools based on request received.<br>Right now, I’ll show pt (i). During chat client initialization, the default set of tools as well as the system prompt are configured as below:</p><pre>@Autowired<br>public CustomerSupportAssistant(@Qualifier(&quot;ragChatClientBuilder&quot;) ChatClient.Builder chatClientBuilder,<br>                                @Qualifier(&quot;tools&quot;) List&lt;ToolCallback&gt; toolCallbacks,<br>                                @Value(&quot;classpath:templates/systemTemplate.st&quot;)<br>                                Resource systemTemplate) {<br>    chatClient = chatClientBuilder<br>            .defaultSystem(systemTemplate)<br>            .defaultToolCallbacks(toolCallbacks)<br>            .build();<br>}</pre><p>10. Finally, expose an API for the frontend:</p><pre>@RestController<br>@RequestMapping(&quot;api&quot;)<br>@RequiredArgsConstructor<br>public class AssistantController {<br>    private final CustomerSupportAssistant agent;<br><br>    @GetMapping(&quot;chat&quot;)<br>    public ResponseEntity&lt;String&gt; chat(@RequestHeader(&quot;userId&quot;) String userId,<br>                                       @RequestParam(&quot;message&quot;) String message) {<br>        return agent.chat(userId, message);<br>    }</pre><pre>public ResponseEntity&lt;String&gt; chat(String userId, String userMessageContent) {<br>    var response = this.chatClient.prompt()<br>            .system(s -&gt; s.param(&quot;current_date&quot;, LocalDate.now().toString()))<br>            .user(userMessageContent)<br>            .advisors(a -&gt; a.param(CONVERSATION_ID, userId))<br>            .call().content();<br>    return ResponseEntity.ok(response);<br>}</pre><p>LLM maintains the chat memory using CONVERSATION_ID (which I’ve mapped to user_id here). It records all the requests made by the user and response shared by the LLM. This data will be used by LLM further for the subsequent requests so that it understands the context that it is dealing with an user.<br>But as the chat progresses, the chat history grows. Is the LLM retrieving all the chat history data?<br>No. LLMs are stateless. We are using sliding window (with fixed size: 10) and sending the last 10 conversations only.</p><h3><em>Conclusion</em></h3><p>This setup demonstrates how to build a customer support chatbot using Spring Boot, Qdrant for semantic search, Gemini for LLM capabilities, and H2 for chat memory.</p><p>You can find the full implementation here: <a href="https://github.com/debmalyapan53/hotel-booking-customer-support">https://github.com/debmalyapan53/hotel-booking-customer-support</a></p><p>Let me know if you want me to start a series on Spring AI tutorials, to go over the fundamentals like prompt stuffing, RAG, Tool calling, MCP etc.</p><p>#springboot #ai #chatbot #rag #toolcalling #vectordatabase #java</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c146356b79a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first FAANG interview experience]]></title>
            <link>https://medium.com/@debmalyapan98/my-first-faang-interview-experience-7527c6a1dce8?source=rss-e25cd5dd254b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7527c6a1dce8</guid>
            <category><![CDATA[faang-interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[faang]]></category>
            <dc:creator><![CDATA[Debmalya Pan]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 20:37:11 GMT</pubDate>
            <atom:updated>2025-07-02T20:47:51.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apple SWE Interview Experience</h3><p>I applied for Software Engineer — Java,Spring-Boot,Microservices role at Apple for Hyderabad, India location via the careers portal.<br>Honestly, this was my first FAANG interview, so was a bit nervous but excited as well.</p><p>My resume got shortlisted and recruiter reached out with an OA.<br>For detailed OA questions refer here: <a href="https://leetcode.com/discuss/post/6766815/apple-oa-ist-swe-hyd-by-debmalyapan53-mnfz/">https://leetcode.com/discuss/post/6766815/apple-oa-ist-swe-hyd-by-debmalyapan53-mnfz/</a></p><p>After 2 weeks, recruiter reached out to schedule 2 elimination rounds. Both the rounds were virtual and had to be completed on the same day.</p><p><strong>Round #1:</strong><br>Interviewer was an ICT3 with 4 YOE. Interview happened during IST timezone.<br>I was asked a simple and yet most common DSA problem: Trapping Rain Water.<br>I gave both the approaches (with extra space and without) and coded it.<br>Then I was grilled on some Java and Spring Boot related topics.<br>1. Multiple questions were asked on Spring Cloud components and their use cases.<br>2. How is default method used in interfaces?<br>3. Differences between Spring MVC vs Spring Boot?<br>4. Comparator vs Comparable<br>5. Describe CAP theorem<br>6. Explain Lambda expressions<br>7. Multiple questions on micro-services resiliency aspects like rate limiting, circuit breaking.<br>8. Explain Factory design pattern with examples.<br>Problem solving was alloted 30 min and rest of the discussion went on for another 30 min.</p><p><strong>Round #2:</strong><br>Interviewer was an SSE with 12+ YOE. Interview happened during IST timezone.<br>This was a system design round. I was asked to design BookMyShow end to end. The functional requirements revolved around the booking flow, onboarding of shows, searching nearby cinema halls and analytics.<br>Luckily, I had completed the CodeKarle youtube playlist (shoutout to Sandeep Kaul) and I was able to ace this round. This discussion went for 40 min.<br>For the rest 20 min, I was again grilled on Java &amp; Spring Boot theoretical aspects.<br>1. Spring cache related aspects<br>2. BeanFactory vs ApplicationContext<br>3. Concurrent collections e.g ConcurrentHashMap<br>4. What’s a Future?<br>Overall feedback was positive and 3 further rounds were scheduled the following week on consecutive days.</p><p><strong>Round #3:<br></strong>Interviewer was an EM with 15+ YOE. Interview happened during PST timezone.<br>This round was entirely behavioral and standard Amazon template type questions were asked. First 15 min was intro.<br>1. Tell me a time when you innovated.<br>2. Tell me a time when you had a disagreement with peer.<br>3. Tell me a time when you delivered in short time and reprioritized work.<br>4. Tell me a time when you used some new technology in the project.<br>5. Tell me a time when….<br>All answers were to be given in STAR format with supporting metrics (if possible). Interview lasted for 1 hr.</p><p><strong>Round #4:<br></strong>Interviewer was an SWE with 15+ YOE. Interview happened during PST timezone.<br>This round covered various aspects from Java to HLD to DSA.<br>1. Create an immutable class. Full working code is expected.<br>2. Design TinyURL. This is a frequently asked interview question and if someone has read Alex Xu: System Design Interview, he/she should be able to solve this seamlessly.<br>Explained 2 approaches: Base62 and MD5 Hash and explained its pros and cons.<br>3. Given an array with repeating elements, return top K frequent elements.</p><p><strong>Round #5:<br></strong>Interview happened during PST timezone after 1 week due to rescheduling conflicts.<br>1. Implement LRU Cache. Full working code was expected along with test cases. Solved it using HashMap and Doubly LinkedList.<br>Follow-up: Was asked to make the code thread-safe. Used ReentrantReadWriteLock and replaced HashMap with ConcurrentHashMap.<br>Follow-up: Was asked for the time and space complexity. <br>This went on for 40 min.<br>Finally, some Java topics were touched upon for the remaining 20 min.<br>1. What is String intern?<br>2. Why do we need to override equals() and hashCode() method?</p><p>Overall, my take is that Apple doesn’t have a clear defined interview process. The process depends on the role you’re interviewing for. So, you need to be prepared well.</p><p>Hope this helps. All the best!!</p><p>#faang #apple #swe #java #microservices #hyderabad</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7527c6a1dce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Config-driven Rule Design Pattern]]></title>
            <link>https://medium.com/@debmalyapan98/config-driven-rule-design-pattern-aa24b5c79901?source=rss-e25cd5dd254b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa24b5c79901</guid>
            <category><![CDATA[multi-tenant-architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[solid-principles-in-java]]></category>
            <category><![CDATA[rule-engine]]></category>
            <dc:creator><![CDATA[Debmalya Pan]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 14:06:33 GMT</pubDate>
            <atom:updated>2025-09-15T16:17:31.845Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem Statement</h3><p>I was going through our legacy application’s code repo and saw there were a bunch of if conditions being executed on an object and inside each if block, fat business logic wasimplemented. At a glance I was overwhelmed to see such a big function with multiple conditions and huge logic in just one file. I did some study and came across this beautiful pattern called Rule Design Pattern. In a minute, we&#39;ll see how this can make code more <strong>modular, readable, testable and maintainable.</strong></p><p>Let’s take the <strong>problem</strong> at hand:<br>A seller signs up at seller.walmart.com and while onboarding, fills up the form, sets up his/her payments, shipping, tax profile info etc and after filling up all the pre-requisites expect to be launched so that he/she can start doing business.<br>Now, we need to keep in mind about tenancy as well, since the seller could be from US or from International (CA, MX or CL) background and each market has its own governing laws and validations that need to be performed.<br>How do we go about this?</p><h4>Naive Approach:</h4><p>The legacy code that existed, had all sort of permutations and combinations of if and switch statements. e.g:</p><pre>private AllenLaunchResponse updateSellerActivationAllen(PartnerDTO partner, AllenLaunchResponse allenLaunchResponse) throws BusinessException {<br>    LOGGER.info(&quot;Seller {} requested for launch&quot;, partnerPk);<br>    var partner = partnerManager.getPartnerByPrimaryKey(partnerPk);<br>    var partnerId = partner.getAttributes().getPartnerId();<br>    var businessUnit = BusinessUnit.getBusinessUnit(partner.getBuId());<br>    if (BusinessUnit.WALMART_US == businessUnit) {<br>      if (Objects.nonNull(partner.getBusinessAttributes()) &amp;&amp; ALLEN.equalsIgnoreCase(<br>          partner.getBusinessAttributes().getOnboardingFlavour())) {<br> <br>        if (isAllenProfileEnable &amp;&amp; !checkPartnerStoreAttributes(partner)) {<br>          LOGGER.info(<br>              &quot;Allen Seller {} cannot be launched as partnerStore attributes are not checked.&quot;,<br>              partnerId);<br>          markSellerForManualReview(partner);<br>          return allenLaunchResponse;<br>        }<br> <br>        if (isAllenPaymentEnable &amp;&amp; isPaymentStatusInactive(partner)) {<br>          LOGGER.info(<br>              &quot;Allen Seller {} cannot be launched as payment method {} not setup.&quot;,<br>              partnerId, partner.getAttributes().getPaymentProcessor());<br>          markSellerForManualReview(partner);<br>          return allenLaunchResponse;<br>        }<br> <br>        if (isAllenInventoryEnable &amp;&amp; validateInventoryExist(partnerId)) {<br>          LOGGER.info(&quot;Inventory is not setup for Allen Seller {}.&quot;, partnerId);<br>          markSellerForManualReview(partner);<br>          return allenLaunchResponse;<br>        }<br>        if (isAllenTnsEnable) {<br>          var geCRMRecordDTO = gecrmAdapter.isTNSApprovedToLaunchSellers(<br>              partnerId);<br>          if (!TNS_STATUS_APPROVED.equalsIgnoreCase(geCRMRecordDTO.getTnsStatus())) {<br>            LOGGER.info(<br>                &quot;Allen Seller {} cannot be launched as Integration Channel or TNS verification fails.&quot;,<br>                partnerId);<br>            markSellerForManualReview(partner, false);<br>            return allenLaunchResponse;<br>          }<br>        }<br>        markSellerAsLive(partner);        // All checks are passing. Allen Seller can be marked live.<br>      }<br>    } else {<br>      var partnerId = partner.getAttributes().getPartnerId();<br>      var buId = partner.getBuId();<br>      if (Objects.nonNull(partner.getBusinessAttributes()) &amp;&amp; ALLEN.equalsIgnoreCase(<br>          partner.getBusinessAttributes().getOnboardingFlavour())) {<br>        if (validateAllowedMart(isAllenIntlPaymentEnable, partner.getMartId())<br>            &amp;&amp; isPaymentStatusInactive(partnerId, partner.getId(),<br>            partner.getAttributes().getPaymentProcessor(), buId)) {<br>          return allenLaunchResponse;<br>        }<br> <br>        //validating BV completion.<br>        if (validateAllowedMart(isAllenIntlProfileEnable, partner.getMartId())<br>            &amp;&amp; !checkPartnerStoreAttributes(partner)) {<br>          return allenLaunchResponse;<br>        }<br> <br>        //validtaing BD approval for CA sellers<br>        if (validateAllowedMart(isAllenBdEnable, partner.getMartId())) {<br>          var geCRMRecordDTO = gecrmAdapter.isBDApprovedToLaunchSellers(<br>              String.valueOf(partnerId));<br>          if (!APPROVED.equalsIgnoreCase(geCRMRecordDTO.getBdStatus())) {<br>            LOGGER.info(&quot;{} Allen Seller {} cannot be launched as BD is not approved&quot;,<br>                BusinessUnit.getBusinessUnit(buId).getBusinessUnitName(), partnerId);<br>            return allenLaunchResponse;<br>          }<br>        }<br> <br>        if (validateAllowedMart(isAllenSellerNumberEnable, partner.getMartId())<br>            &amp;&amp; !checkPartnerSellerNumber(partner)) {<br>          LOGGER.info(<br>              &quot;{} Allen Seller {} cannot be launched as sellerNumber attributes is not present&quot;,<br>              BusinessUnit.getBusinessUnit(buId).getBusinessUnitName(), partnerId);<br>          return allenLaunchResponse;<br>        }<br> <br>        //validating EBS approval for CL sellers<br>        if (validateAllowedMart(isAllenEBSEnable, partner.getMartId())) {<br>          var geCRMRecordDTO = gecrmAdapter.isEBSApprovedToLaunchSeller(<br>              String.valueOf(partnerId));<br>          if (!APPROVED.equalsIgnoreCase(geCRMRecordDTO.getEbsStatus())) {<br>            LOGGER.info(&quot;{} Allen Seller {} cannot be launched as EBS is not approved&quot;,<br>                BusinessUnit.getBusinessUnit(buId).getBusinessUnitName(), partnerId);<br>            return allenLaunchResponse;<br>          }<br>        }<br> <br>        if (!this.checkAMLStatus(partner)) {<br>          LOGGER.info(<br>              &quot;{} Allen Seller {} cannot be launched as AML Compliance verification failed.&quot;,<br>              BusinessUnit.getBusinessUnit(buId).getBusinessUnitName(), partnerId);<br>          return allenLaunchResponse;<br>        }<br> <br>      }<br> <br>      if (Objects.nonNull(buId) &amp;&amp; BusinessUnit.WALMART_MEXICO.getBusinessUnitId()<br>          .equalsIgnoreCase(buId)) {<br>        if (!checkPartnerSellerNumber(partner)) {<br>          LOGGER.info(<br>              &quot;Seller {} cannot be launched as sellerNumber attributes is not present&quot;,<br>              partnerId);<br>          return allenLaunchResponse;<br>        }<br> <br>      }<br> <br>      LOGGER.info(&quot;Marking Seller {} as active on Site.&quot;, partnerId);<br>      markSellerAsLive(partner);<br>      return allenLaunchResponse;<br>    }<br>  }</pre><p>See how complex and dense it looks like. All the conditions, rules are being done in just one function. It doesnt clearly obey SOLID principles where, in order to add new rule, we need to make changes in this function by adding extra if condition and testing is required for whole class. My god!!! Imagine writing JUnit for this function 😣. You would need a whole bottle of coffee 😛.</p><h4>Scalable Approach:</h4><p>While writing our V2 applications, we decided to implement Rule Design Pattern <em>(which is nothing but a combination of Template Method and Command patterns following SOLID principles)</em>. This takes care of the clumsy if-else blocks and would make it easier to plug-in new validations. This solves pluggability of new validations.<br>How do we solve multi-tenancy when it comes to different markets having different kinds of validations? Thats where config driven approach comes into picture. Imagine each rule as a spring bean. Now we have a bunch of rules/beans and we just need to specify for which market, what are the list of beans to be invoked. Sounds simple enough.</p><p><strong>Step 1: Defining ConfigProvider</strong></p><pre>public class ConfigProvider&lt;T&gt; {<br> <br>  private final Resource configResource;<br>  private final ObjectMapper objectMapper;<br>  private final ConfigModel&lt;T&gt; conf;<br>  private final JavaType genericsType;<br>  public static final String BU_ID_MART_ID_FORMAT = &quot;%s::%s&quot;;<br>  public static final String BIZ_ROLE_FORMAT = &quot;%s/%s&quot;;<br> <br>  public ConfigProvider(Resource configResource, ObjectMapper objectMapper) throws IOException {<br>    this.configResource = configResource;<br>    this.objectMapper = objectMapper;<br> <br>    Type superClass = this.getClass().getGenericSuperclass();<br>    if (superClass instanceof Class) {<br>      throw new IllegalArgumentException(&quot;Internal error: ConfigProvider constructed without actual type information&quot;);<br>    } else {<br>      Class&lt;T&gt; type = (Class&lt;T&gt;) ((ParameterizedType) superClass).getActualTypeArguments()[0];<br>      this.genericsType = objectMapper.constructType(type);<br>    }<br>    this.conf = this.loadConfig();<br>  }<br> <br>  private ConfigModel&lt;T&gt; loadConfig() throws IOException {<br>    var config = ServiceUtil.getResourceAsString(configResource);<br>    var pType = this.objectMapper.getTypeFactory()<br>        .constructParametricType(ConfigModel.class, this.genericsType);<br>    return this.objectMapper.readValue(config, pType);<br>  }<br> <br>  public Object getConfig(String key, String buId, String martId, String bizRole)<br>      throws NoSuchFieldException, IllegalAccessException {<br>    var buAndMartId = String.format(BU_ID_MART_ID_FORMAT, buId, martId);<br>    var buAndMartIdAndRole = String.format(BIZ_ROLE_FORMAT, buAndMartId,<br>        bizRole);<br> <br>    Map&lt;String, T&gt; overrides = ((ConfigModel) this.conf).getConfigOverrides();<br> <br>    T response = overrides.getOrDefault(buAndMartIdAndRole,<br>        overrides.getOrDefault(buAndMartId, null));<br>    if (response == null) {<br>      response = this.conf.getConfigDefinitions();<br>    }<br> <br>    Object value = getValue(key, response);<br>    return (value == null) ? getValue(key, this.conf.getConfigDefinitions()) : value;<br>  }<br>  public Object getDefaultConfig(String key)<br>      throws NoSuchFieldException, IllegalAccessException {<br>    T response = this.conf.getConfigDefinitions();<br>    Object value = getValue(key, response);<br>    return (value == null) ? getValue(key, this.conf.getConfigDefinitions()) : value;<br>  }<br> <br>  private Object getValue(String key, T configFetched) throws NoSuchFieldException, IllegalAccessException {<br>    Field field = null;<br>    try {<br>      field = configFetched.getClass().getDeclaredField(key);<br>    } catch (NoSuchFieldException e) {<br>      field = configFetched.getClass().getSuperclass().getDeclaredField(key);<br>    }<br>    field.setAccessible(true);<br>    Object value = field.get(configFetched);<br>    field.setAccessible(false);<br>    return value;<br>  }<br>}</pre><p><strong>Step 2: Defining Resource File</strong></p><pre>{<br>  &quot;configDefinitions&quot;: null,<br>  &quot;configOverrides&quot;: {<br>    &quot;0::0/SELLER&quot;: {            //US Market<br>      &quot;onboardingFlavour&quot;: {<br>        &quot;ALLEN&quot;: [<br>          &quot;businessProfileValidationCommand&quot;,<br>          &quot;profileValidationCommand&quot;,<br>          &quot;paymentStatusValidationCommand&quot;,<br>          &quot;updateSellerBannerFlagsCommand&quot;<br>        ],<br>        &quot;NON_ALLEN&quot;: [<br>          &quot;profileValidationCommand&quot;,<br>          &quot;paymentStatusValidationCommand&quot;,<br>          &quot;tnsValidationCommand&quot;,<br>          &quot;inventoryValidationCommand&quot;,<br>          &quot;applyWfsCommand&quot;,<br>          &quot;updateSellerBannerFlagsCommand&quot;<br>        ]<br>      }<br>    },<br>    &quot;1::1/SELLER&quot;: {            //CA Market<br>      &quot;onboardingFlavour&quot;: {<br>        &quot;ALLEN&quot;: [<br>          &quot;businessProfileValidationCommand&quot;,<br>          &quot;profileValidationCommand&quot;,<br>          &quot;amlComplianceValidationCommand&quot;,<br>          &quot;bdValidationCommand&quot;,<br>          &quot;paymentStatusValidationCommand&quot;,<br>          &quot;updateSellerBannerFlagsCommand&quot;<br>        ],<br>        &quot;NON_ALLEN&quot;: []<br>      }<br>    },<br>    &quot;7::7/SELLER&quot;: {            //MX Market<br>      &quot;onboardingFlavour&quot;: {<br>        &quot;ALLEN&quot;: [<br>          &quot;businessProfileValidationCommand&quot;,<br>          &quot;profileValidationCommand&quot;,<br>          &quot;amlComplianceValidationCommand&quot;,<br>          &quot;sellerNumberValidationCommand&quot;,<br>          &quot;paymentStatusValidationCommand&quot;,<br>          &quot;updateSellerBannerFlagsCommand&quot;<br>        ],<br>        &quot;NON_ALLEN&quot;: [<br>          &quot;sellerNumberValidationCommand&quot;,<br>          &quot;updateSellerBannerFlagsCommand&quot;<br>        ]<br>      }<br>    },<br>    &quot;306::306/SELLER&quot;: {        //CL Market<br>      &quot;onboardingFlavour&quot;: {<br>        &quot;ALLEN&quot;: [<br>          &quot;businessProfileValidationCommand&quot;,<br>          &quot;profileValidationCommand&quot;,<br>          &quot;amlComplianceValidationCommand&quot;,<br>          &quot;sellerNumberValidationCommand&quot;,<br>          &quot;ebsValidationCommand&quot;,<br>          &quot;paymentStatusValidationCommand&quot;,<br>          &quot;updateSellerBannerFlagsCommand&quot;<br>        ],<br>        &quot;NON_ALLEN&quot;: [<br>          &quot;updateSellerBannerFlagsCommand&quot;<br>        ]<br>      }<br>    }<br>  }<br>}</pre><p><strong>Step 3: Wiring the beans</strong></p><pre>//DTO for deserialization of the resource config<br>public class PartnerLaunchConfig {<br>  private Map&lt;OnboardingFlavourEnum, List&lt;String&gt;&gt; onboardingFlavour;<br>}<br> <br>@Bean(&quot;partnerLaunchConfigProvider&quot;)<br>public ConfigProvider&lt;PartnerLaunchConfig&gt; getPartnerLaunchConfig(@Value(Constants.PARTNER_LAUNCH_CONFIG_PATH) Resource partnerLaunchConfigResource, ObjectMapper objectMapper) throws IOException {<br>    return new ConfigProvider&lt;&gt;(partnerLaunchConfigResource, objectMapper) {};<br>}</pre><p><strong>Step 4: Create LaunchCommand &amp; LaunchExecutor (Base Framework)</strong></p><pre>//Define LaunchExecutor<br>public class LaunchContextExecutor {<br>  private List&lt;LaunchCommand&gt; commands = new LinkedList&lt;&gt;();<br>  private LaunchContext context;<br> <br>  public LaunchContextExecutor attachContext(LaunchContext context) {<br>    this.context = context;<br>    return this;<br>  }<br> <br>  @SneakyThrows<br>  public LaunchContextExecutor addCommand(String beanName) {<br>    commands.add(BeanUtils.getBean(beanName, LaunchCommand.class));<br>    return this;<br>  }<br> <br>  public LaunchContextExecutor execute() throws BaseException {<br>    if (CollectionUtils.isNotEmpty(commands)) {<br>      for (LaunchCommand command : commands) {<br>        executeCommand(command, context);<br>      }<br>    }<br>    return this;<br>  }<br> <br>  private void executeCommand(LaunchCommand command, LaunchContext launchContext) throws BaseException {<br>    try {<br>      command.execute(launchContext);<br>    } catch (BaseException baseException) {<br>      var errorMsg = baseException.getErrors().stream().map(Error::getDescription).collect(Collectors.joining());<br>      log.error(&quot;Launch command execution failed with errorMessage=&quot; + errorMsg, baseException);<br>      throw baseException;<br>    } catch (Exception exception) {<br>      log.error(&quot;Launch command execution failed with errorMessage=&quot; + exception.getMessage(), exception);<br>      throw new BaseException(BaseError.UNKNOWN_ERR);<br>    }<br>  }<br>}<br> <br>//Define LaunchCommand abstract class. Each validation rule class would be extending this.<br>public abstract class LaunchCommand {<br> <br>  public LaunchContext execute(LaunchContext launchContext) throws BaseException {<br>    executeRequest(launchContext);<br>    return launchContext;<br>  }<br> <br>  protected abstract void executeRequest(LaunchContext launchContext) throws BaseException;<br>}<br> <br>//Define LaunchContext<br>public class LaunchContext extends ConcurrentHashMap&lt;String, Object&gt; {<br>  public &lt;T&gt; T getVariable(String key) {<br>    return (T) get(key);<br>  }<br> <br>  public void setVariable(String key, Object value) {<br>    put(key, value);<br>  }<br>}</pre><p><strong>Step 5: Defining the validator beans</strong></p><pre>@Component(&quot;ebsValidationCommand&quot;)<br>@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)<br>public class EBSValidationCommand extends LaunchCommand {<br> <br>  private final GecrmAdapter gecrmAdapter;<br> <br>  @Autowired<br>  public EBSValidationCommand(GecrmAdapter gecrmAdapter) {<br>    this.gecrmAdapter = gecrmAdapter;<br>  }<br> <br>  @Override<br>  protected void executeRequest(LaunchContext launchContext) throws BaseException {<br>    var partner = launchContext.getVariable(LaunchConstants.PARTNER);<br>    var context = launchContext.getVariable(LaunchConstants.CONTEXT);<br>    var tnsQuery =  &quot;&quot;; //TnS Query defined here       <br>    var partnerId = partner.getPartnerId();<br>    var gecrmRecord = gecrmAdapter.getGECRMStatus(partnerId, tnsQuery);<br>    if (!GecrmConstants.APPROVED.equalsIgnoreCase(gecrmRecord.getEbsStatus())) {<br>      log.error(&quot;Seller launch failed for partnerId={} reason=EBS is not approved&quot;, partnerId);<br>      throw new LaunchException(PartnerError.EBS_NOT_APPROVED_ERR, partnerId);<br>    }<br>  }<br>}</pre><p><strong>Step 6: Putting the pieces together</strong></p><pre>var launchConfig = LaunchUtils.getConfig(context);<br>var launchCommands = launchConfig.getOnboardingFlavour().get(partnerDto.getOnboardingFlavour());<br>var launchContext = new LaunchContext();<br>launchContext.setVariable(LaunchConstants.PARTNER, partnerDto);<br>launchContext.setVariable(LaunchConstants.CONTEXT, context);<br>var launchContextExecutor = new LaunchContextExecutor().attachContext(launchContext);<br>launchCommands.forEach(launchContextExecutor::addCommand);<br>try {<br>  launchContextExecutor.execute();<br>} catch (LaunchException e) {<br>  log.info(&quot;Seller sent for manual review, partnerId={}.&quot;, partnerDto.getPartnerId());<br>  throw e;<br>}</pre><h3>Conclusion:</h3><ol><li>Writing JUnit made easy. Each class now represent one and only one rule. So, its easier now to write test cases.</li><li>The design aligns with SOLID principles. Tomorrow, if there is a new business rule, we just need to implement a new concrete class from LaunchCommand, which supports Open Closed Principle.</li></ol><p>Lastly, using design patterns is fancy but we shouldn’t use for each and every problem. Before using any design pattern, make sure you are not over engineering the code.</p><p>Thank you for reading till here and please give a clap to the story if you like it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa24b5c79901" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying gRPC]]></title>
            <link>https://medium.com/@debmalyapan98/demystifying-grpc-63202cb8f92e?source=rss-e25cd5dd254b------2</link>
            <guid isPermaLink="false">https://medium.com/p/63202cb8f92e</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[demystifying-technology]]></category>
            <dc:creator><![CDATA[Debmalya Pan]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 11:14:23 GMT</pubDate>
            <atom:updated>2024-06-15T11:26:30.708Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re in the software industry for the last few years, you must be familiar with SOAP, GraphQL, RESTful web services but since 2015, gRPC has been gaining traction slowly and turning heads in the industry due to its low latency inter-service communication.</p><p><strong>What is a RPC?</strong> Simply put, its a Remote Procedure Call, which means when a procedure in another address space (another compute) could be invoked from a different address space as if that procedure call was a local one.</p><p><strong><em>gRPC</em></strong><em> is a high performance RPC framework/technology built by Google and uses HTTP/2 instead of HTTP/1.1 and “Google’s own” protocol buffers instead of XML or JSON for data contract.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/0*cKe_1vF6FDiPRcmS.png" /></figure><p><strong>What is a Protobuf, you ask? </strong>“Protocol Buffers” is a open-source message format for data serialization, as the default method of communication between client and server.</p><h3>JSON/XML vs Protobuf ! Advantages and its disadvantages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSIrI5bQzPdJujl2ByuS7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*XUJjaO7FA3Za7lnS.png" /><figcaption>Rough Architecture</figcaption></figure><h3>gRPC = HTTP/2 + Protobuf. So, How is it faster than REST ?</h3><p>Lets dig deep into why Google and Uber uses gRPC for building their low latency systems.</p><p><strong>HTTP/1.1</strong></p><ul><li>Headers are sent at every request and are plaintext.</li><li>Each request opens a TCP connection, hence adding to latency and increase in network packet size.</li></ul><p><strong>HTTP/2</strong></p><ul><li>HTTP/2 supports multiplexing, i.e Client and Server can push messages in parallel over same TCP connection, which reduces latency.</li><li>HTTP/2 supports server push. Server can push streams (multi-messages) for one request from client.</li><li>HTTP/2 supports header compression.</li><li><strong>HTTP/2 is binary. </strong>(Protobuf is a binary protocol and makes a great match for HTTP/2)</li><li>HTTP/2 is secure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*0PNM0zQfh91o2zId.jpeg" /></figure><p>To summarise, in HTTP/2, there is less chatter, less use of bandwidth, reduced latency and increased security.</p><h3>Types of API in gRPC:</h3><ol><li><strong>Unary</strong> — Simple client server communication</li><li><strong>Server Streaming </strong>— This is the case where client will send a single request and server can send back multiple response. Example of this: When client send request for homepage with multiple item list, server can send back responses separately, making client enable lazy loading.</li><li><strong>Client Streaming </strong>— Here, client will send multiple requests and server will only send back a single response. Example of this: Zip/chunk files upload by client.</li><li><strong>Bidirectional Streaming</strong> — This is streaming where both client and server will sequences of message all together without waiting for the response.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypHn77QJlzND0HktEKEqOw.png" /><figcaption>Types of gRPC APIs</figcaption></figure><pre>message GreetRequest {<br>    string name = 1;<br>    string description = 2;<br>    int32 id = 3;<br>}<br> <br>message GreetResponse {<br>    string processedMessage = 1;<br>}<br> <br>service GreetService {<br>    //Unary<br>    rpc greet(GreetRequest) returns (GreetResponse) {};<br>    //Server Streaming<br>    rpc greetManyTimes(GreetManyTimesRequest) returns (stream GreetManyTimesResponse) {};<br>    //Client Streaming<br>    rpc longGreet(stream LongGreetRequest) returns (LongGreetResponse) {};<br>    //Bi-directional<br>    rpc greetEveryone(stream GreetEveryoneRequest) returns (stream GreetEveryoneResponse) {};<br>}</pre><h3>gRPC vs REST vs GraphQL. Who wins?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eDmiT4pXT1Gzs2IL.png" /></figure><p><strong>Please note</strong> that gRPC is not a replacement for REST or GraphQL, it is another technology option which is based on RPC having its own advantages and disadvantages and one must evaluate the different technologies to suit their business needs.</p><p><strong>REST vs gRPC — Benchmark Tests:</strong></p><p>I am adding the references of couple of other medium articles which explains the benchmark tests performed.</p><p><strong><em>References</em></strong>:</p><ol><li><a href="https://medium.com/@i.gorton/scaling-up-rest-versus-grpc-benchmark-tests-551f73ed88d4">https://medium.com/@i.gorton/scaling-up-rest-versus-grpc-benchmark-tests-551f73ed88d4</a></li><li><a href="https://medium.com/@EmperorRXF/evaluating-performance-of-rest-vs-grpc-1b8bdf0b22da">https://medium.com/@EmperorRXF/evaluating-performance-of-rest-vs-grpc-1b8bdf0b22da</a></li></ol><h3>When to use gRPC?</h3><ol><li><em>Internal Systems especially service to service synchronous communication </em>— Since gRPC uses HTTP/2 and protocol buffers it offers better performance, less bandwidth requirements.</li><li><em>Real time data streaming</em> — As gRPC supports client side, server side and bi-directional streaming under HTTP/2. This makes it well suited for applications like ride share applications, etc.</li><li><em>Native Mobile applications backend</em> — As gRPC offers small payload size and more speed, it can enhance the user experience and reduce the latency and bandwidth.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*G7GYvW0gfTVSi4Qa.jpeg" /></figure><h3>When to not use gRPC? Drawbacks of gRPC!</h3><ol><li><em>Browser based apps</em> — It is not possible to call gRPC APIs directly from browsers owing to lack of full support for HTTP/2 by browsers. Though there is gRPC-web proxy available through which browser based application can consume gRPC APIs, but again there are certain limitations and hence for a pure browser based apps gRPC is not well suited for now.</li><li><em>Legacy Systems</em> — Scenarios where integration is required with legacy systems, gRPC will not be a right fit there as legacy system may not support gRPC.</li><li><em>gRPC is not a replacement for WebSockets</em>, since WebSocket is designed more for web browser to server communication whereas gRPC is more suited for server-to-server communications.</li></ol><p>What I shared here is just the surface of gRPC, but this should help you guys to understand about what gRPC is and what does it provides, how it roughly works. I hope to explain how to implement a gRPC service using SpringBoot in a future article.</p><p><strong><em>Resources:</em></strong></p><ol><li><a href="https://grpc.io/">https://grpc.io/</a></li><li><a href="https://www.altexsoft.com/blog/what-is-grpc/">https://www.altexsoft.com/blog/what-is-grpc/</a></li><li><a href="https://protobuf.dev/overview/">https://protobuf.dev/overview/</a></li><li><a href="https://developers.google.com/protocol-buffers">https://developers.google.com/protocol-buffers</a></li><li><a href="https://medium.com/javarevisited/what-are-protocol-buffers-and-why-they-are-widely-used-cbcb04d378b6">https://medium.com/javarevisited/what-are-protocol-buffers-and-why-they-are-widely-used-cbcb04d378b6</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63202cb8f92e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>