<?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 Dilip Kumar Jha  on Medium]]></title>
        <description><![CDATA[Stories by Dilip Kumar Jha  on Medium]]></description>
        <link>https://medium.com/@dildeepak?source=rss-f4faf5ec48e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MNDxbGJljz50gakzf-05Pg.jpeg</url>
            <title>Stories by Dilip Kumar Jha  on Medium</title>
            <link>https://medium.com/@dildeepak?source=rss-f4faf5ec48e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:03:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dildeepak/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[Switch Expression Evolution in Java]]></title>
            <link>https://dildeepak.medium.com/switch-expression-evolution-in-java-d93ca45e3727?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d93ca45e3727</guid>
            <category><![CDATA[java17]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java21]]></category>
            <category><![CDATA[switch-case-in-java]]></category>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 02:54:30 GMT</pubDate>
            <atom:updated>2026-08-30T02:54:30.506Z</atom:updated>
            <content:encoded><![CDATA[<p>Switch statement in java has seen a great evolution pre-java 7 version till java 21.</p><blockquote>Before Java 7, we could only use primitive integral types (byte, short, char, int), their corresponding Wrapper classes, and enum types. If we wanted to compare strings, we had to use a chain of if-else statements with .equals()</blockquote><pre>int value = 5;<br>switch (value) {<br>    case 1:<br>        System.out.println(&quot;One&quot;);<br>        break;<br>    case 5:<br>        System.out.println(&quot;five&quot;);<br>        break;<br>    default:<br>        System.out.println(&quot;Unknown&quot;);<br>}</pre><p><a href="https://dildeepak.medium.com/kafka-interview-question-for-experienced-professional-15202727bee0">Kafka Interview Question — For Experienced Professional</a></p><h3>Java 7: Switch Statement</h3><blockquote>From Java 7, Strings were introduced in case values and switch statements started to evolve</blockquote><p><em>String Switch Case :</em></p><pre>String day = &quot;Tuesday&quot;;<br>        switch (day) {<br>            case &quot;Monday&quot;:<br>                System.out.println(&quot;Week day&quot;);<br>                break;<br>            case &quot;Tuesday&quot;:<br>                System.out.println(&quot;Week day&quot;);<br>                break;<br>            case &quot;Wednesday&quot;:<br>                System.out.println(&quot;Week day&quot;);<br>                break;<br>            case &quot;Thursday&quot;:<br>                System.out.println(&quot;Week day&quot;);<br>                break;<br>            case &quot;Friday&quot;:<br>                System.out.println(&quot;Week day&quot;);<br>                break;<br>            case &quot;Saturday&quot;:<br>                System.out.println(&quot;Weekend&quot;);<br>                break;<br>            case &quot;Sunday&quot;:<br>                System.out.println(&quot;Weekend&quot;);<br>                break;<br>            default:<br>                System.out.println(&quot;Unknown&quot;);<br>        }</pre><p><a href="https://dildeepak.medium.com/kubernetes-interview-questions-for-experienced-you-shouldnt-attend-any-exam-without-them-755696861b30">Kubernetes Interview Questions for Experienced — You shouldn’t attend any exam without them</a></p><h3>Java 12 : Switch Statement</h3><blockquote>Java 12 further enhanced the switch statement and introduced switch expressions as a <em>preview </em>feature.</blockquote><p>It introduced a flurry of new features:</p><ul><li>We can return values from a switch block and hence switch statements became <strong><em>switch expressions</em></strong></li><li>We can have multiple values in a case label</li><li>We can return value from a switch expression through the arrow operator or through the “break” keyword</li></ul><p><strong>Return value through break keyword</strong></p><pre>return  switch (day) {<br>    case &quot;Monday&quot;:<br>        break &quot;Weekday&quot;;<br>    case &quot;Tuesday&quot;:<br>        break &quot;Weekday&quot;;<br>    case &quot;Wednesday&quot;:<br>        break &quot;Weekday&quot;;<br>    case &quot;Thursday&quot;:<br>        break &quot;Weekday&quot;;<br>    case &quot;Friday&quot;:<br>        break &quot;Weekday&quot;;<br>    case &quot;Saturday&quot;:<br>        break &quot;Weekend&quot;;<br>    case &quot;Sunday&quot;:<br>        break &quot;Weekend&quot;;<br>    default:<br>        break &quot;Unknown&quot;;<br>};</pre><p>The word “break” can be used to return the result value.</p><blockquote><em>This word was replaced by “yield” later in Java 13.</em></blockquote><pre>return  switch (day) {<br>    case &quot;Monday&quot;:<br>        yield  &quot;Weekday&quot;;<br>    case &quot;Tuesday&quot;:<br>        yield &quot;Weekday&quot;;<br>    case &quot;Wednesday&quot;:<br>        yield &quot;Weekday&quot;;<br>    case &quot;Thursday&quot;:<br>        yield &quot;Weekday&quot;;<br>    case &quot;Friday&quot;:<br>        yield &quot;Weekday&quot;;<br>    case &quot;Saturday&quot;:<br>        yield &quot;Weekend&quot;;<br>    case &quot;Sunday&quot;:<br>        yield &quot;Weekend&quot;;<br>    default:<br>        yield &quot;Unknown&quot;;<br>};</pre><p><strong>Return value through arrow operator :</strong></p><p>Further instead of returning values using break keyword , Java 12 introduced arrow operators as a simple alternative:</p><pre>return  switch (day) {<br>            case &quot;Monday&quot;-&gt; &quot;Week day&quot;;<br>            case &quot;Tuesday&quot;-&gt; &quot;Week day&quot;;<br>            case &quot;Wednesday&quot;-&gt;&quot;Week day&quot;;<br>            case &quot;Thursday&quot;-&gt;&quot;Week day&quot;;<br>            case &quot;Friday&quot;-&gt;&quot;Week day&quot;;<br>            case &quot;Saturday&quot;-&gt; &quot;Weekend&quot;;<br>            case &quot;Sunday&quot;-&gt; &quot;Weekend&quot;;<br>            default-&gt;&quot;Unknown&quot;;<br>        };</pre><p><strong>Multiple case labels :</strong></p><p>Also starting Java 12 multiple case values could be provided in a single case statement , So if we observe above example since all 5 case expected here same value so instead of return one by one i can merge or combine multiple case value to single one like below</p><pre>return  switch (day) {<br>            case &quot;Monday&quot;,&quot;Tuesday&quot;,&quot;Wednesday&quot;,&quot;Thursday&quot;,&quot;Friday&quot;<br>-&gt; &quot;Week day&quot;;<br>            case &quot;Saturday&quot;, &quot;Sunday&quot; -&gt; &quot;Weekend&quot;;<br>            default-&gt;&quot;Unknown&quot;;<br>        };</pre><p><a href="https://dildeepak.medium.com/case-study-system-design-round-for-banking-tech-giant-012928eb256e">Case study / System Design Round for Banking Tech Giant</a></p><h3>Java 14 : Switch Statement changes</h3><p>What ever switch statement &amp; features we discussed so far in java 12 and 13 those are preview features to access that The flag –enable-preview need to set true .<br>But Java 14 just made all the features permanent from being a preview feature<br>The flag –enable-preview need not be set starting java 14. &amp; switch statements have evolved into switch expressions!</p><p><a href="https://dildeepak.medium.com/design-a-global-payment-transaction-processing-and-ledger-system-aa0410114ee2">“Design a global payment transaction processing and ledger system.”</a></p><h3>Java 17 : Switch Statement / Expression (Preview Feature) :</h3><blockquote>Java 17 LTS is the latest long-term support release for the Java SE platform and it was released<strong> on </strong><strong>September 15, 2021.</strong></blockquote><p>Switch expression features</p><ol><li>Pattern matching</li><li>Gaurded pattern — For additional checks</li><li>Null cases</li></ol><h3>Pattern Matching :</h3><p>It has introduced a new feature for switch i.e called <strong><em>pattern matching.</em></strong></p><p>We can match patterns in a case label.</p><p>In other words we can pass objects in switch condition and this object can be checked for different types in switch case labels.</p><pre>return switch (obj) {<br>    case Integer i -&gt; &quot;It is an integer&quot;;<br>    case String s -&gt; &quot;It is a string&quot;;<br>    case Employee emp-&gt; &quot;It is a Employee&quot;;<br>     default -&gt; &quot;It is none of the known data types&quot;;<br>};</pre><p>In the above example I am passing an object to the switch condition. This was not possible until Java 17. And then this object can be checked for a particular data type and assigned to a variable as well.</p><p>For example consider the case :</p><p>case Integer i- &gt; &quot;It is an integer&quot;;</p><p>The passed object is checked for the type “Integer” and then assigned to the variable “i” if it is an integer. And through the arrow operator the string “It is an integer ” is returned .</p><h3>Gaurded Patterns :</h3><p>Let’s take this use case.</p><p>Inside the case label where I have checked for a “Employee” instance , I want to do an additional check.</p><p>Thinking traditionally , we could be doing this after the case statement.</p><p>Something like this:</p><p>case Employee emp:</p><p>if(emp.getDept().equals(&quot;HR&quot;)) {</p><p>yield &quot;HR Employee&quot;;</p><p>}</p><p>But Java 17 has introduced “Guarded Patterns” . We can do this check in the case label itself like below</p><pre>return switch (obj) {<br>    case Integer i -&gt; &quot;It is an integer&quot;;<br>    case String s -&gt; &quot;It is a string&quot;;<br>    case Employee emp &amp;&amp; emp.getDept().equals(&quot;HR&quot;) -&gt; &quot;HR Employee&quot;;<br>    default -&gt; &quot;It is none of the known data types&quot;;<br>};</pre><p><a href="https://dildeepak.medium.com/design-a-global-payment-transaction-processing-and-ledger-system-shorter-version-77f63495a91b">“Design a global payment transaction processing and ledger system.” — Shorter Version</a></p><h3>Null Cases :</h3><p>We could never pass a null value to switch statements prior to Java 17 without a Null pointer exception being thrown.</p><p>Java 17 allows us to handle it this way</p><p>case null -&gt; &quot;It is a null object&quot;;</p><p>If we have the above switch expression we will never get Null Pointer exception if the object we pass is null.</p><p><a href="https://dildeepak.medium.com/spring-batch-how-it-works-real-time-answers-for-experienced-profession-d036b17cbee0">Spring Batch — How it works . Real time answers for Experienced profession</a></p><h3>Java 21: Switch Statement / Expression (standardized and enhanced) :</h3><blockquote>Java 21 LTS is the latest long-term support release for the Java SE platform and it was released<strong> on </strong>September 19, 2023<strong>.</strong></blockquote><p>Switch expression features</p><ol><li>Pattern matching</li><li>Guarded pattern using when— For additional checks</li><li>Native Null handling</li></ol><p>In Java 21, we are no longer limited to primitives, Strings, and enums. We can switch on an Object, check its type, and automatically cast it into a case-scoped pattern variable.</p><pre>public String formatter(Object obj) {<br>    return switch (obj) {<br>        case Integer i -&gt; String.format(&quot;int %d&quot;, i);<br>        case Long l    -&gt; String.format(&quot;long %d&quot;, l);<br>        case Double d  -&gt; String.format(&quot;double %f&quot;, d);<br>        case String s  -&gt; String.format(&quot;String %s&quot;, s);<br>        default        -&gt; obj.toString();<br>    };<br>}</pre><p>We can refine our type patterns by appending a boolean condition using the when keyword. This replaces the older preview keyword &amp;&amp;.</p><pre>String response = switch (obj) {<br>    case String s when s.equalsIgnoreCase(&quot;YES&quot;) -&gt; &quot;User agreed.&quot;;<br>    case String s when s.equalsIgnoreCase(&quot;NO&quot;)  -&gt; &quot;User declined.&quot;;<br>    case String s                                -&gt; &quot;User gave an unhandled response: &quot; + s;<br>    default                                      -&gt; &quot;Not a string&quot;;<br>};</pre><p>Historically, passing a null value into a switch threw a NullPointerException. Java 21 allows you to handle null safely as an explicit case label.</p><pre>return switch (obj) {<br>    case null     -&gt; &quot;Object is null!&quot;;<br>    case String s -&gt; &quot;It&#39;s a string: &quot; + s;<br>    default       -&gt; &quot;It&#39;s something else&quot;;<br>};</pre><h3>Conclusion:</h3><p>The evolution of the switch statement in Java demonstrates a clear trend toward greater flexibility and power, enabling more concise, readable, and maintainable code. From basic integer-based switches to powerful pattern-based expressions in Java 17 and 21, the switch statement has grown to support more complex logic and a wider variety of use case.</p><p>That’s all about the journey for switch case journey . Hope you like this article . if yes do follow me on medium now :)</p><ul><li><a href="https://dildeepak.medium.com/rest-api-microservices-and-kafka-interview-questions-for-experienced-professional-b254db53fea9">Rest API , Microservices and Kafka Interview Questions for Experienced Professional</a></li><li><a href="https://dildeepak.medium.com/spring-core-and-spring-boot-interview-questions-for-experienced-professional-75b18da2a176">Spring Core and Spring Boot Interview Questions for Experienced Professional</a></li><li><a href="https://dildeepak.medium.com/top-30-spring-boot-interview-questions-with-answers-for-experienced-java-developer-764e9172239d">Top 30 Spring Boot Interview Questions with Answers for Experienced Java Developer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d93ca45e3727" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rest API , Microservices and Kafka Interview Questions for Experienced Professional]]></title>
            <link>https://dildeepak.medium.com/rest-api-microservices-and-kafka-interview-questions-for-experienced-professional-b254db53fea9?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b254db53fea9</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 05:55:09 GMT</pubDate>
            <atom:updated>2026-07-22T05:55:09.254Z</atom:updated>
            <content:encoded><![CDATA[<h3>REST API Questions</h3><h3>1. What is REST API?</h3><p>REST API is a way for applications to communicate over HTTP. In Spring Boot, we expose REST APIs using @RestController.</p><p>Common HTTP methods are:</p><p>POST /api/v1/payments<br>GET /api/v1/payments/{paymentId}<br>PATCH /api/v1/payments/{paymentId}<br>DELETE /api/v1/payments/{paymentId}</p><p>In my projects, REST APIs were used for communication between frontend and backend or between microservices.</p><h3>2. Difference between @Controller and @RestController</h3><p>@Controller is used in MVC applications to return views.</p><p>@RestController is used in REST APIs to return JSON or XML response directly.</p><p>@RestController is basically:</p><pre>@Controller + @ResponseBody</pre><p>Example:</p><pre>@RestController<br>@RequestMapping(&quot;/api/users&quot;)<br>public class UserController {<br>}</pre><p>For microservices, I mostly use @RestController.</p><h3>3. What is @RequestMapping?</h3><p>@RequestMapping is used to map HTTP requests to controller methods or classes.</p><p>Example:</p><pre>@RequestMapping(&quot;/api/orders&quot;)<br>@RestController<br>public class OrderController {<br>}</pre><p>We can also use specialized annotations:</p><pre>@GetMapping<br>@PostMapping<br>@PutMapping<br>@DeleteMapping</pre><p>These are more readable and commonly used.</p><h3>4. Difference between @GetMapping and @PostMapping</h3><p>@GetMapping is used to fetch data.</p><pre>@GetMapping(&quot;/users/{id}&quot;)<br>public User getUser(@PathVariable Long id) {<br>    return userService.getUser(id);<br>}</pre><p>@PostMapping is used to create data.</p><pre>@PostMapping(&quot;/users&quot;)<br>public User createUser(@RequestBody UserRequest request) {<br>    return userService.createUser(request);<br>}</pre><p>GET should not modify data. POST usually creates a new resource.</p><h3>5. Difference between @PathVariable and @RequestParam</h3><p>@PathVariable gets value from the URL path.</p><pre>@GetMapping(&quot;/users/{id}&quot;)<br>public User getUser(@PathVariable Long id) {<br>}</pre><p>URL:</p><pre>/users/10</pre><p>@RequestParam gets value from query parameters.</p><pre>@GetMapping(&quot;/users&quot;)<br>public List&lt;User&gt; getUsers(@RequestParam String status) {<br>}</pre><p>URL:</p><pre>/users?status=ACTIVE</pre><p>I use @PathVariable for identifying a specific resource and @RequestParam for filtering, sorting, or pagination.</p><h3>6. What is @RequestBody?</h3><p>@RequestBody is used to read JSON request data and convert it into a Java object.</p><p>Example:</p><pre>@PostMapping(&quot;/payments&quot;)<br>public PaymentResponse createPayment(@RequestBody PaymentRequest request) {<br>    return paymentService.createPayment(request);<br>}</pre><p>Spring uses Jackson internally to convert JSON into Java objects.</p><h3>7. What is ResponseEntity?</h3><p>ResponseEntity is used to control HTTP response status, headers, and body.</p><p>Example:</p><pre>return ResponseEntity.status(HttpStatus.CREATED).body(response);</pre><p>It is useful when we want to return proper status codes like:</p><pre>200 OK<br>201 CREATED<br>400 BAD REQUEST<br>404 NOT FOUND<br>500 INTERNAL SERVER ERROR</pre><p>In production APIs, proper status codes are important for clients and other microservices.</p><h3>8. How do you handle validation in Spring Boot?</h3><p>I use validation annotations in DTO classes.</p><p>Example:</p><pre>public class UserRequest {</pre><pre>    @NotBlank<br>    private String name;</pre><pre>    @Email<br>    private String email;</pre><pre>    @NotNull<br>    private Integer age;<br>}</pre><p>In controller:</p><pre>@PostMapping(&quot;/users&quot;)<br>public ResponseEntity&lt;UserResponse&gt; createUser(@Valid @RequestBody UserRequest request) {<br>    return ResponseEntity.ok(userService.createUser(request));<br>}</pre><p>If validation fails, Spring throws an exception, and we handle it globally.</p><h3>Exception Handling Questions</h3><h3>9. How do you handle exceptions globally?</h3><p>I use @ControllerAdvice with @ExceptionHandler.</p><p>Example:</p><pre>@RestControllerAdvice<br>public class GlobalExceptionHandler {</pre><pre>    @ExceptionHandler(UserNotFoundException.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleUserNotFound(UserNotFoundException ex) {<br>        ErrorResponse error = new ErrorResponse(&quot;USER_NOT_FOUND&quot;, ex.getMessage());<br>        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);<br>    }<br>}</pre><p>This gives a consistent error response for all APIs.</p><h3>10. Why should we avoid try-catch in every controller?</h3><p>If we write try-catch in every controller, the code becomes repetitive and hard to maintain. Instead, we should throw custom exceptions from service classes and handle them in one place using @ControllerAdvice.</p><p>This keeps controller code clean and makes error handling consistent.</p><h3>11. What are common HTTP status codes used in REST APIs?</h3><p>Common HTTP status codes in REST APIs are grouped into five categories.</p><h3>1xx — Informational</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiK5AUBEc4GpnUY5v2OqEA.png" /></figure><h3>2xx — Successful</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MYdtTcQDBmoikEkFr9sY-w.png" /></figure><p>Example:</p><pre>POST /api/payments</pre><pre>HTTP/1.1 201 Created<br>Location: /api/payments/PAY-123</pre><h3>3xx — Redirection and caching</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWWiMLWSK9ED-voE69FILw.png" /></figure><h3>4xx — Client errors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*AlMc0SWIUB-gPVtuFEf9ag.png" /></figure><h3>Important distinction</h3><ul><li>401: “You are not authenticated.”</li><li>403: “You are authenticated, but you are not allowed.”</li><li>400: Technical request validation failed.</li><li>422: Request is syntactically correct, but business validation failed.</li><li>409: The operation conflicts with the current state.</li></ul><h3>5xx — Server errors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*tR4LXfQ9naFn4C2gelp9vg.png" /></figure><h3>Payment API example</h3><pre>POST /api/v1/payments</pre><p>Possible responses:</p><pre>201 Created        Payment successfully created<br>400 Bad Request    Invalid JSON or missing accountId<br>401 Unauthorized   Missing or expired token<br>403 Forbidden      User cannot debit this account<br>404 Not Found      Account does not exist<br>409 Conflict       Duplicate idempotency key<br>422 Unprocessable Content<br>                   Insufficient balance or invalid amount<br>429 Too Many Requests<br>                   Rate limit exceeded<br>500 Internal Server Error<br>                   Unexpected application failure<br>503 Service Unavailable<br>                   Payment service temporarily unavailable</pre><p>A good REST API should also return a consistent error body:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2026-07-22T10:30:00Z&quot;,<br>  &quot;status&quot;: 409,<br>  &quot;error&quot;: &quot;Conflict&quot;,<br>  &quot;code&quot;: &quot;DUPLICATE_PAYMENT&quot;,<br>  &quot;message&quot;: &quot;A payment already exists for the supplied idempotency key.&quot;,<br>  &quot;path&quot;: &quot;/api/v1/payments&quot;,<br>  &quot;correlationId&quot;: &quot;abc-123&quot;<br>}</pre><h3>12. What is the difference between POST, PUT, and PATCH?</h3><h3>POST</h3><p>Creates a new resource or executes a non-idempotent operation.</p><pre>POST /payments</pre><p>Calling it multiple times can create multiple payments unless idempotency protection is implemented.</p><h3>PUT</h3><p>Completely creates or replaces a resource at a known URI.</p><pre>PUT /customers/123/preferences</pre><p>PUT should be idempotent.</p><h3>PATCH</h3><p>Partially updates a resource.</p><pre>PATCH /customers/123</pre><pre>{<br>  &quot;phoneNumber&quot;: &quot;1234567890&quot;<br>}</pre><p>PATCH can be idempotent depending on how the operation is designed.</p><h3><strong>13. What is idempotency, and why is it important?</strong></h3><p>An idempotent operation produces the same final result whether it is executed once or multiple times.</p><p>This is especially important in payment systems because clients may retry requests after timeouts.</p><p>Example:</p><pre>POST /payments<br>Idempotency-Key: txn-123456</pre><p>The server stores:</p><pre>idempotency_key<br>request_hash<br>response_status<br>response_body<br>created_at</pre><p>When the same key is received again:</p><ul><li>If the request body matches, return the previous response.</li><li>If the body differs, return 409 Conflict.</li><li>Do not create another payment.</li></ul><p>GET, PUT, and DELETE should normally be idempotent. POST is not inherently idempotent, but it can be designed that way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b254db53fea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Batch — How it works . Real time answers for Experienced profession]]></title>
            <link>https://dildeepak.medium.com/spring-batch-how-it-works-real-time-answers-for-experienced-profession-d036b17cbee0?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d036b17cbee0</guid>
            <category><![CDATA[spring-batch]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 07:23:10 GMT</pubDate>
            <atom:updated>2026-07-19T07:23:10.352Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Batch is a framework for processing large volumes of data in a reliable, restartable, and controlled way. I have typically used it for workloads such as transaction reconciliation, file ingestion, database migration, settlement processing, and scheduled reporting.</p><h3>How Spring Batch works</h3><p>The main hierarchy is:</p><pre>Job<br> └── Step<br>      ├── ItemReader<br>      ├── ItemProcessor<br>      └── ItemWriter</pre><h3>1. Job</h3><p>A Job represents the complete batch process.</p><p>For example:</p><pre>Daily Payment Reconciliation Job</pre><p>A job can contain one or more steps:</p><pre>Step 1: Read payment transactions<br>Step 2: Validate and reconcile them<br>Step 3: Generate exception report</pre><h3>2. Step</h3><p>A Step is an individual phase of a job.</p><p>Spring Batch mainly supports two step styles:</p><ul><li>Chunk-oriented processing</li><li>Tasklet-based processing</li></ul><p>For large datasets, chunk-oriented processing is more commonly used.</p><h3>3. Chunk-oriented processing</h3><p>Suppose the chunk size is 100.</p><p>Spring Batch will:</p><ol><li>Read 100 records.</li><li>Process each record.</li><li>Write the 100 processed records.</li><li>Commit the transaction.</li><li>Continue with the next 100 records.</li></ol><p>Conceptually:</p><pre>Read → Process → Write → Commit</pre><p>This avoids loading millions of records into memory at once.</p><h3>4. ItemReader</h3><p>The reader retrieves one record at a time from a source such as:</p><ul><li>CSV or fixed-width files</li><li>Database</li><li>JSON or XML</li><li>Kafka or another external system through custom readers</li></ul><p>Examples include:</p><pre>JdbcPagingItemReader<br>JpaPagingItemReader<br>FlatFileItemReader</pre><h3>5. ItemProcessor</h3><p>The processor applies business logic.</p><p>For example:</p><ul><li>Validate fields</li><li>Convert data formats</li><li>Remove invalid records</li><li>Calculate fees</li><li>Enrich data</li><li>Compare source and ledger transactions</li></ul><p>A processor can return null to filter out a record.</p><h3>6. ItemWriter</h3><p>The writer persists or publishes the processed records.</p><p>For example:</p><ul><li>Insert or update database records</li><li>Write a reconciliation report</li><li>Generate a CSV file</li><li>Publish messages to Kafka</li></ul><h3>7. JobRepository</h3><p>The JobRepository stores batch metadata, including:</p><ul><li>Job instance</li><li>Job execution</li><li>Step execution</li><li>Start and end times</li><li>Execution status</li><li>Commit count</li><li>Rollback count</li><li>Read and write count</li></ul><p>Spring Batch uses metadata tables such as:</p><pre>BATCH_JOB_INSTANCE<br>BATCH_JOB_EXECUTION<br>BATCH_STEP_EXECUTION<br>BATCH_JOB_EXECUTION_PARAMS</pre><p>This metadata makes restart and monitoring possible.</p><h3>8. JobLauncher</h3><p>The JobLauncher starts a job with a set of job parameters.</p><pre>jobLauncher.run(job, jobParameters);</pre><p>Job parameters uniquely identify a job instance.</p><p>For example:</p><pre>businessDate = 2026-07-12<br>fileName = payment_20260712.csv</pre><h3>How I would describe my implementation in an interview</h3><p>In one of my previous projects, we used Spring Batch to process a large volume of financial transaction records received from upstream systems.</p><p>The batch job was responsible for reading transaction records, validating them, transforming them into our internal format, comparing them with existing payment or ledger records, and storing the final reconciliation status.</p><p>We designed the job using chunk-oriented processing.</p><p>The ItemReader read records from a database using JdbcPagingItemReader. We preferred a paging reader instead of loading the entire result set into memory because the volume could be several hundred thousand or millions of records.</p><p>The ItemProcessor contained the main validation and transformation logic. It validated mandatory fields such as transaction ID, account ID, currency, amount, and timestamp. It also checked duplicate transaction IDs, converted external status codes into our internal status, and classified transactions as matched, unmatched, or requiring manual investigation.</p><p>The ItemWriter used batch database operations to insert or update the reconciliation results. Instead of executing one database statement per record, we wrote records in batches to reduce database round trips and improve throughput.</p><p>We configured a chunk size based on performance testing. For example, we started with 100 records per chunk and later increased it depending on database capacity, record size, and transaction duration.</p><p>We also configured fault tolerance. Transient exceptions, such as temporary database connection or timeout issues, were retried a limited number of times. Records with permanent validation errors were skipped and written to an exception table with the reason for failure.</p><p>Spring Batch stored job and step execution details in its metadata tables. This allowed us to monitor processed counts, failed counts, skipped records, execution duration, and restart failed jobs.</p><p>For restartability, we made sure the reader was stateful and that every successfully committed chunk updated the JobRepository. If the job failed after processing 500,000 records, it did not restart from the beginning. It resumed from the last committed checkpoint.</p><p>We also made the writer idempotent. We used the transaction ID or another business key with a database unique constraint and upsert logic. This prevented duplicate records if the same file was submitted again or if a job was restarted.</p><p>For large independent datasets, we used partitioning. The master step divided records by account range, date range, or transaction ID range, and worker steps processed those partitions in parallel. We controlled the thread pool size so that parallel processing did not overload the database.</p><p>We added listeners such as JobExecutionListener and StepExecutionListener for logging, operational metrics, notifications, and audit reporting. At the end of the job, we generated a summary containing total records, successful records, rejected records, duplicate records, and reconciliation exceptions.</p><p>The overall focus was not only processing speed, but also restartability, idempotency, auditability, controlled retries, and operational visibility because those qualities are especially important in financial batch processing.</p><h3>Simplified Spring Batch configuration</h3><pre>@Configuration<br>@EnableBatchProcessing<br>public class PaymentBatchConfiguration {</pre><pre>    @Bean<br>    public Job paymentReconciliationJob(<br>            JobRepository jobRepository,<br>            Step paymentProcessingStep) {</pre><pre>        return new JobBuilder(<br>                &quot;paymentReconciliationJob&quot;,<br>                jobRepository)<br>                .start(paymentProcessingStep)<br>                .build();<br>    }</pre><pre>    @Bean<br>    public Step paymentProcessingStep(<br>            JobRepository jobRepository,<br>            PlatformTransactionManager transactionManager,<br>            ItemReader&lt;PaymentRecord&gt; paymentReader,<br>            ItemProcessor&lt;PaymentRecord, ReconciliationRecord&gt; paymentProcessor,<br>            ItemWriter&lt;ReconciliationRecord&gt; paymentWriter) {</pre><pre>        return new StepBuilder(<br>                &quot;paymentProcessingStep&quot;,<br>                jobRepository)<br>                .&lt;PaymentRecord, ReconciliationRecord&gt;chunk(<br>                        500,<br>                        transactionManager)<br>                .reader(paymentReader)<br>                .processor(paymentProcessor)<br>                .writer(paymentWriter)<br>                .faultTolerant()<br>                .retry(TransientDataAccessException.class)<br>                .retryLimit(3)<br>                .skip(InvalidPaymentException.class)<br>                .skipLimit(1_000)<br>                .build();<br>    }<br>}</pre><h3>Example processor</h3><pre>@Component<br>public class PaymentProcessor<br>        implements ItemProcessor&lt;PaymentRecord, ReconciliationRecord&gt; {</pre><pre>    @Override<br>    public ReconciliationRecord process(PaymentRecord payment) {</pre><pre>        validate(payment);</pre><pre>        return new ReconciliationRecord(<br>                payment.transactionId(),<br>                payment.userId(),<br>                payment.amount(),<br>                determineStatus(payment)<br>        );<br>    }</pre><pre>    private void validate(PaymentRecord payment) {<br>        if (payment.transactionId() == null<br>                || payment.transactionId().isBlank()) {<br>            throw new InvalidPaymentException(<br>                    &quot;Transaction ID is missing&quot;);<br>        }</pre><pre>        if (payment.amount() == null<br>                || payment.amount().signum() &lt; 0) {<br>            throw new InvalidPaymentException(<br>                    &quot;Invalid payment amount&quot;);<br>        }<br>    }</pre><pre>    private String determineStatus(PaymentRecord payment) {<br>        return &quot;MATCHED&quot;;<br>    }<br>}</pre><h3>Restartability</h3><p>Spring Batch does not simply remember the record number in application memory. It saves execution state in the JobRepository.</p><p>For a paging reader, it can persist information such as:</p><pre>Current page<br>Current item count<br>Step execution status<br>Last committed checkpoint</pre><p>Suppose the chunk size is 500:</p><pre>Records 1–500: committed<br>Records 501–1000: committed<br>Records 1001–1500: failure</pre><p>After restart, the job resumes from the last successfully committed state rather than processing everything again.</p><p>However, restartability must be supported by the application design. The writer should still be idempotent because a crash can happen at uncertain points between an external side effect and metadata update.</p><h3>Retry versus skip</h3><p>Use retry for temporary failures:</p><pre>Database deadlock<br>Temporary network failure<br>Service timeout<br>Connection reset</pre><p>Use skip for data-specific permanent failures:</p><pre>Invalid date<br>Missing user ID<br>Malformed account number<br>Unsupported currency</pre><p>Example:</p><pre>.faultTolerant()<br>.retry(DeadlockLoserDataAccessException.class)<br>.retryLimit(3)<br>.skip(InvalidPaymentException.class)<br>.skipLimit(1000)</pre><p>I would not retry every exception because retrying a validation error repeatedly provides no benefit.</p><h3>Parallel processing options</h3><p>Spring Batch supports several scaling strategies.</p><h3>Multi-threaded step</h3><p>Multiple chunks are processed concurrently within one step.</p><p>Good for moderate parallelism, but the reader and writer must be thread-safe.</p><h3>Partitioning</h3><p>A master step divides work into partitions:</p><pre>Partition 1: IDs 1–100,000<br>Partition 2: IDs 100,001–200,000<br>Partition 3: IDs 200,001–300,000</pre><p>Worker steps process partitions in parallel.</p><p>This is usually easier to control and reason about for very large database workloads.</p><h3>Remote partitioning or remote chunking</h3><p>Work is distributed across multiple JVMs or containers, often using messaging.</p><p>This is useful when a single application instance cannot meet the processing window.</p><h3>Important production considerations</h3><p>For a payment system, I would emphasize:</p><ul><li>Use a business key or transaction ID for idempotency.</li><li>Add a unique database constraint as the final protection against duplicates.</li><li>Tune chunk size through performance testing.</li><li>Avoid very large chunks because failures cause the whole chunk to roll back.</li><li>Avoid very small chunks because they create too many commits and database calls.</li><li>Ensure readers and writers are safe before enabling multithreading.</li><li>Store rejected records with failure reasons.</li><li>Add operational dashboards and alerts.</li><li>Reconcile source count, processed count, skipped count, and output count.</li><li>Pass a business date or file identifier as a job parameter.</li><li>Prevent two job instances from processing the same business input concurrently.</li></ul><h3>Strong closing answer</h3><blockquote><em>“Spring Batch gives us a structured way to process large datasets through jobs and steps, normally using reader, processor, and writer components. Its major advantages are chunk-based transactions, restartability, retry and skip handling, job metadata, and support for parallel processing. In my implementation, I used it for financial transaction processing and reconciliation, where the most important design concerns were not only throughput, but also idempotency, checkpoint-based restart, auditability, controlled error handling, and ensuring that rerunning a job never produced duplicate financial records.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d036b17cbee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Design a global payment transaction processing and ledger system.” — Shorter Version]]></title>
            <link>https://dildeepak.medium.com/design-a-global-payment-transaction-processing-and-ledger-system-shorter-version-77f63495a91b?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/77f63495a91b</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[capital-one]]></category>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 10:21:08 GMT</pubDate>
            <atom:updated>2026-07-12T10:21:08.997Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been asked a Case/Design question like this, then you should try to cover as much as you could from Functional requirement to non — functional requirement, DB, Messaging, Security, DLQ, Audit etc.</p><p>Here is a <strong>Senior Lead-level system design</strong> , tailored for a banking tech- savvy companies like Capital One.</p><h3>1. Problem Statement</h3><p>Design a system that can process global payment transactions across multiple countries, currencies, merchants, banks, and payment rails.</p><p>You must cover:</p><p><strong>Functional requirements</strong></p><ul><li>Create payment transaction</li><li>Validate customer/account/card/payment method</li><li>Authorize payment</li><li>Post debit/credit ledger entries</li><li>Publish transaction events</li><li>Track status: PENDING, AUTHORIZED, POSTED, FAILED, REVERSED</li><li>Support idempotent retries</li><li>Support reconciliation</li><li>Support audit and regulatory traceability</li></ul><p><strong>Non-functional requirements</strong></p><ul><li>High availability</li><li>Strong consistency for ledger writes</li><li>Eventual consistency for notifications/reporting</li><li>Low latency for authorization path</li><li>High throughput</li><li>Secure PII/payment data handling</li><li>Observability</li><li>Disaster recovery</li><li>Auditability</li></ul><p><a href="https://dildeepak.medium.com/kafka-interview-question-for-experienced-professional-15202727bee0">Kafka Interview Question — For Experienced Professional</a></p><p><strong>Core services</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*QVRDSF1EZN2PSN_vLRqRpw.png" /></figure><p><strong>Sample APIs</strong></p><p>POST /payments<br>GET /payments/{paymentId}<br>POST /payments/{paymentId}/cancel<br>POST /payments/{paymentId}/reverse<br>GET /accounts/{accountId}/ledger<br>GET /reconciliation/runs/{runId}</p><p>Request:</p><p>{<br> “idempotencyKey”: “client-123-payment-456”,<br> “sourceAccountId”: “A123”,<br> “destinationAccountId”: “B456”,<br> “amount”: 250.00,<br> “currency”: “USD”,<br> “paymentType”: “ACH”,<br> “metadata”: {<br> “channel”: “WEB”<br> }<br>}</p><p><a href="https://dildeepak.medium.com/kubernetes-interview-questions-for-experienced-you-shouldnt-attend-any-exam-without-them-755696861b30">Kubernetes Interview Questions for Experienced — You shouldn’t attend any exam without them</a></p><p><strong>DB schema</strong></p><p>CREATE TABLE payment_transaction (<br> payment_id UUID PRIMARY KEY,<br> idempotency_key VARCHAR(100) UNIQUE NOT NULL,<br> source_account_id VARCHAR(50) NOT NULL,<br> destination_account_id VARCHAR(50) NOT NULL,<br> amount DECIMAL(18,2) NOT NULL,<br> currency CHAR(3) NOT NULL,<br> status VARCHAR(30) NOT NULL,<br> failure_reason VARCHAR(255),<br> created_at TIMESTAMP NOT NULL,<br> updated_at TIMESTAMP NOT NULL<br>);</p><p>CREATE TABLE ledger_entry (<br> ledger_entry_id UUID PRIMARY KEY,<br> payment_id UUID NOT NULL,<br> account_id VARCHAR(50) NOT NULL,<br> entry_type VARCHAR(10) NOT NULL, — DEBIT / CREDIT<br> amount DECIMAL(18,2) NOT NULL,<br> currency CHAR(3) NOT NULL,<br> balance_after DECIMAL(18,2),<br> created_at TIMESTAMP NOT NULL<br>);</p><p>CREATE TABLE audit_event (<br> audit_id UUID PRIMARY KEY,<br> entity_id UUID NOT NULL,<br> entity_type VARCHAR(50) NOT NULL,<br> event_type VARCHAR(50) NOT NULL,<br> old_value JSONB,<br> new_value JSONB,<br> actor VARCHAR(100),<br> correlation_id VARCHAR(100),<br> created_at TIMESTAMP NOT NULL<br>);</p><p>CREATE TABLE reconciliation_result (<br> reconciliation_id UUID PRIMARY KEY,<br> payment_id UUID NOT NULL,<br> internal_status VARCHAR(30),<br> external_status VARCHAR(30),<br> difference_reason VARCHAR(255),<br> resolution_status VARCHAR(30),<br> created_at TIMESTAMP NOT NULL<br>);</p><p><strong>Kafka topics</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*PJfCwCyBGCvdIWFB24XAYQ.png" /></figure><p><a href="https://dildeepak.medium.com/case-study-system-design-round-for-banking-tech-giant-012928eb256e">Case study / System Design Round for Banking Tech Giant</a></p><p><strong>Idempotency approach</strong></p><p>Explain this clearly:</p><p>“The client sends an idempotency key. Before creating a new payment, the Payment Orchestrator checks whether that key already exists. If it exists, we return the original payment response instead of creating a duplicate. At the database level, I enforce a unique constraint on idempotency_key. For Kafka consumers, I also store processed event IDs to avoid duplicate side effects.”</p><p><strong>Retry and DLQ</strong></p><p>Use this answer:</p><p>“For transient failures, such as network timeout, I use bounded retries with exponential backoff. For permanent failures, such as validation failure, I do not retry. If retries are exhausted, the message goes to a DLQ with correlation ID, failure reason, payload reference, and retry count. DLQ messages are monitored and can be replayed after fixing the root cause.”</p><p><strong>Reconciliation</strong></p><p>Say this:</p><p>“At the end of the day or near-real-time intervals, the reconciliation service compares internal payment/ledger records with external network settlement files or events. Any mismatch is written to a reconciliation table and published to reconciliation.mismatch.detected. Operations can review, auto-resolve known patterns, or trigger adjustment/reversal flows.”</p><blockquote><strong>If you are interested in detailed one, please read this one:</strong></blockquote><p><a href="https://dildeepak.medium.com/design-a-global-payment-transaction-processing-and-ledger-system-aa0410114ee2">“Design a global payment transaction processing and ledger system.”</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77f63495a91b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Design a global payment transaction processing and ledger system.”]]></title>
            <link>https://dildeepak.medium.com/design-a-global-payment-transaction-processing-and-ledger-system-aa0410114ee2?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa0410114ee2</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 08:46:46 GMT</pubDate>
            <atom:updated>2026-07-11T08:46:46.756Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been asked a Case/Design question like this, then you should try to cover as much as you could from Functional requirement to non — functional requirement, DB, Messaging, Security, DLQ, Audit etc.</p><p>Here is a <strong>Senior Lead-level system design</strong> , tailored for a banking tech- savvy companies like Capital One.</p><h3>1. Problem Statement</h3><p>Design a system that can process global payment transactions across multiple countries, currencies, merchants, banks, and payment rails.</p><p>The system should support:</p><ul><li>Payment initiation</li><li>Validation</li><li>Fraud/risk checks</li><li>FX conversion</li><li>Routing to payment networks</li><li>Ledger posting</li><li>Idempotency</li><li>Retry and DLQ</li><li>Auditability</li><li>Reconciliation</li><li>High availability and scalability</li></ul><p>The most important principle:</p><blockquote><strong><em>The ledger is the source of truth. Payment status can change, external systems can fail, but every money movement must be recorded immutably using double-entry accounting.</em></strong></blockquote><h3>2. High-Level Architecture</h3><pre>Client / Merchant / Partner<br>        |<br>        v<br>API Gateway<br>        |<br>        v<br>Payment Orchestrator<br>        |<br>        +--&gt; Validation Service<br>        |<br>        +--&gt; Fraud / Risk Service<br>        |<br>        +--&gt; FX Service<br>        |<br>        +--&gt; Routing Service<br>        |<br>        +--&gt; Payment Rail Adapter<br>        |        |<br>        |        +--&gt; ACH / Wire / Card Network / RTP / SWIFT<br>        |<br>        +--&gt; Ledger Service<br>        |<br>        +--&gt; Notification Service<br>        |<br>        +--&gt; Reconciliation Service</pre><p>For asynchronous processing:</p><pre>Payment API<br>   |<br>   v<br>Kafka Topic: payment.commands<br>   |<br>   v<br>Payment Orchestrator Consumer<br>   |<br>   v<br>Kafka Topics:<br> - payment.validated<br> - payment.failed<br> - payment.authorized<br> - payment.settled<br> - ledger.posting.requested<br> - ledger.posting.completed<br> - payment.reconciled<br> - payment.dlq</pre><h3>3. Core Services</h3><h3>3.1 API Gateway</h3><p>Responsibilities:</p><ul><li>Authentication and authorization</li><li>Rate limiting</li><li>Request validation</li><li>Idempotency header validation</li><li>Routing to internal services</li></ul><p>Example headers:</p><pre>POST /payments<br>Idempotency-Key: merchant123-order456<br>Authorization: Bearer &lt;token&gt;</pre><h3>3.2 Payment Orchestrator</h3><p>This is the brain of the payment flow.</p><p>Responsibilities:</p><ul><li>Coordinate payment lifecycle</li><li>Call validation, fraud, FX, routing, ledger</li><li>Maintain payment state machine</li><li>Publish events to Kafka</li><li>Handle retries and failures</li></ul><p>Payment states:</p><pre>RECEIVED<br>VALIDATED<br>RISK_APPROVED<br>FX_RESERVED<br>ROUTED<br>PROCESSING<br>AUTHORIZED<br>SETTLED<br>FAILED<br>REVERSED<br>RECONCILED</pre><h3>3.3 Validation Service</h3><p>Validates:</p><ul><li>Required fields</li><li>Amount &gt; 0</li><li>Supported currency</li><li>Valid merchant</li><li>Valid debtor and creditor account</li><li>Duplicate transaction check</li><li>Compliance rules</li><li>Country-specific constraints</li></ul><p>Example validations:</p><pre>USD payment cannot have INR-only payment rail<br>Amount must be positive<br>Merchant must be active<br>Source account must not be blocked<br>Idempotency key must not already be processed differently</pre><h3>3.4 Fraud / Risk Service</h3><p>Responsibilities:</p><ul><li>Velocity checks</li><li>Sanctions screening</li><li>AML rules</li><li>Device/IP risk</li><li>Merchant risk score</li><li>Transaction anomaly detection</li></ul><p>Possible outputs:</p><pre>APPROVED<br>REJECTED<br>MANUAL_REVIEW</pre><h3>3.5 FX Service</h3><p>Used for cross-currency payments.</p><p>Example:</p><pre>Sender pays: 100 USD<br>Receiver gets: 9180 INR<br>FX rate: 91.80<br>Spread: 0.5%</pre><p>Responsibilities:</p><ul><li>Fetch FX rate</li><li>Lock rate temporarily</li><li>Store FX quote</li><li>Expire quote if payment is delayed</li></ul><h3>3.6 Routing Service</h3><p>Chooses the best payment rail.</p><p>Example rules:</p><pre>If domestic US and low cost -&gt; ACH<br>If urgent US payment -&gt; RTP<br>If international high value -&gt; SWIFT<br>If card-based payment -&gt; Card Network</pre><p>Routing considers:</p><ul><li>Country</li><li>Currency</li><li>Cost</li><li>Speed</li><li>Availability</li><li>Rail limits</li><li>Compliance rules</li><li>Bank support</li></ul><h3>3.7 Payment Rail Adapter</h3><p>Each payment rail should have its own adapter.</p><pre>ACH Adapter<br>Wire Adapter<br>Card Network Adapter<br>RTP Adapter<br>SWIFT Adapter<br>UPI Adapter<br>SEPA Adapter</pre><p>Each adapter hides external complexity from the core system.</p><p>Example interface:</p><pre>public interface PaymentRailAdapter {<br>    RailResponse initiatePayment(PaymentInstruction instruction);<br>    RailStatus checkStatus(String externalReferenceId);<br>}</pre><h3>3.8 Ledger Service</h3><p>The ledger is the most critical component.</p><p>It must be:</p><ul><li>Immutable</li><li>Auditable</li><li>Double-entry</li><li>Strongly consistent</li><li>Idempotent</li><li>Append-only</li></ul><p>For every debit, there must be a matching credit.</p><p>Example:</p><p>Customer sends $100 to merchant.</p><pre>Debit  Customer Wallet      100 USD<br>Credit Merchant Receivable  100 USD</pre><p>For fees:</p><pre>Debit  Merchant Receivable  2 USD<br>Credit Fee Revenue          2 USD</pre><p>Final settlement:</p><pre>Debit  Settlement Clearing Account  98 USD<br>Credit Merchant Bank Account        98 USD</pre><h3>4. API Design</h3><h3>4.1 Create Payment</h3><pre>POST /api/v1/payments</pre><p>Request:</p><pre>{<br>  &quot;merchantId&quot;: &quot;M123&quot;,<br>  &quot;customerId&quot;: &quot;C456&quot;,<br>  &quot;sourceAccountId&quot;: &quot;A111&quot;,<br>  &quot;destinationAccountId&quot;: &quot;A999&quot;,<br>  &quot;amount&quot;: 100.00,<br>  &quot;currency&quot;: &quot;USD&quot;,<br>  &quot;destinationCurrency&quot;: &quot;INR&quot;,<br>  &quot;paymentMethod&quot;: &quot;BANK_TRANSFER&quot;,<br>  &quot;country&quot;: &quot;US&quot;,<br>  &quot;metadata&quot;: {<br>    &quot;orderId&quot;: &quot;ORD-789&quot;<br>  }<br>}</pre><p>Response:</p><pre>{<br>  &quot;paymentId&quot;: &quot;PAY-10001&quot;,<br>  &quot;status&quot;: &quot;RECEIVED&quot;,<br>  &quot;message&quot;: &quot;Payment accepted for processing&quot;<br>}</pre><p>For global payments, I would usually avoid doing everything synchronously. The API should accept the request, persist it, publish an event, and allow processing asynchronously.</p><h3>4.2 Get Payment Status</h3><pre>GET /api/v1/payments/{paymentId}</pre><p>Response:</p><pre>{<br>  &quot;paymentId&quot;: &quot;PAY-10001&quot;,<br>  &quot;status&quot;: &quot;SETTLED&quot;,<br>  &quot;amount&quot;: 100.00,<br>  &quot;currency&quot;: &quot;USD&quot;,<br>  &quot;destinationAmount&quot;: 9180.00,<br>  &quot;destinationCurrency&quot;: &quot;INR&quot;,<br>  &quot;rail&quot;: &quot;SWIFT&quot;,<br>  &quot;createdAt&quot;: &quot;2026-07-11T10:15:30Z&quot;,<br>  &quot;updatedAt&quot;: &quot;2026-07-11T10:17:22Z&quot;<br>}</pre><h3>4.3 Refund / Reversal</h3><pre>POST /api/v1/payments/{paymentId}/reversal</pre><p>Request:</p><pre>{<br>  &quot;reason&quot;: &quot;CUSTOMER_REQUEST&quot;,<br>  &quot;amount&quot;: 100.00<br>}</pre><h3>4.4 Ledger Entries</h3><pre>GET /api/v1/ledger/payments/{paymentId}</pre><p>Response:</p><pre>{<br>  &quot;paymentId&quot;: &quot;PAY-10001&quot;,<br>  &quot;entries&quot;: [<br>    {<br>      &quot;entryId&quot;: &quot;LE-1&quot;,<br>      &quot;accountId&quot;: &quot;CUSTOMER_WALLET&quot;,<br>      &quot;type&quot;: &quot;DEBIT&quot;,<br>      &quot;amount&quot;: 100.00,<br>      &quot;currency&quot;: &quot;USD&quot;<br>    },<br>    {<br>      &quot;entryId&quot;: &quot;LE-2&quot;,<br>      &quot;accountId&quot;: &quot;MERCHANT_RECEIVABLE&quot;,<br>      &quot;type&quot;: &quot;CREDIT&quot;,<br>      &quot;amount&quot;: 100.00,<br>      &quot;currency&quot;: &quot;USD&quot;<br>    }<br>  ]<br>}</pre><h3>5. Database Design</h3><p>For payments, I would use a relational database such as PostgreSQL, MySQL, or CockroachDB because consistency matters.</p><h3>5.1 payment_transaction</h3><pre>CREATE TABLE payment_transaction (<br>    payment_id          VARCHAR(64) PRIMARY KEY,<br>    merchant_id         VARCHAR(64) NOT NULL,<br>    customer_id         VARCHAR(64),<br>    source_account_id   VARCHAR(64) NOT NULL,<br>    destination_account_id VARCHAR(64) NOT NULL,<br>    amount              DECIMAL(19, 4) NOT NULL,<br>    currency            VARCHAR(3) NOT NULL,<br>    destination_amount  DECIMAL(19, 4),<br>    destination_currency VARCHAR(3),<br>    status              VARCHAR(32) NOT NULL,<br>    rail                VARCHAR(32),<br>    external_reference_id VARCHAR(128),<br>    idempotency_key     VARCHAR(128) NOT NULL,<br>    failure_reason      TEXT,<br>    created_at          TIMESTAMP NOT NULL,<br>    updated_at          TIMESTAMP NOT NULL,<br>    UNIQUE (merchant_id, idempotency_key)<br>);</pre><h3>5.2 ledger_account</h3><pre>CREATE TABLE ledger_account (<br>    account_id      VARCHAR(64) PRIMARY KEY,<br>    account_type    VARCHAR(32) NOT NULL,<br>    currency        VARCHAR(3) NOT NULL,<br>    owner_id        VARCHAR(64),<br>    status          VARCHAR(32) NOT NULL,<br>    created_at      TIMESTAMP NOT NULL<br>);</pre><p>Examples of account types:</p><pre>CUSTOMER_WALLET<br>MERCHANT_RECEIVABLE<br>FEE_REVENUE<br>SETTLEMENT_CLEARING<br>BANK_ACCOUNT<br>FX_GAIN_LOSS</pre><h3>5.3 ledger_entry</h3><pre>CREATE TABLE ledger_entry (<br>    entry_id        VARCHAR(64) PRIMARY KEY,<br>    transaction_id  VARCHAR(64) NOT NULL,<br>    payment_id      VARCHAR(64) NOT NULL,<br>    account_id      VARCHAR(64) NOT NULL,<br>    entry_type      VARCHAR(10) NOT NULL, -- DEBIT or CREDIT<br>    amount          DECIMAL(19, 4) NOT NULL,<br>    currency        VARCHAR(3) NOT NULL,<br>    created_at      TIMESTAMP NOT NULL<br>);</pre><p>Important rule:</p><pre>For every transaction_id:<br>SUM(DEBITS) must equal SUM(CREDITS)</pre><h3>5.4 ledger_transaction</h3><pre>CREATE TABLE ledger_transaction (<br>    transaction_id    VARCHAR(64) PRIMARY KEY,<br>    payment_id        VARCHAR(64) NOT NULL,<br>    transaction_type  VARCHAR(32) NOT NULL,<br>    status            VARCHAR(32) NOT NULL,<br>    created_at        TIMESTAMP NOT NULL<br>);</pre><p>Examples:</p><pre>AUTHORIZATION<br>CAPTURE<br>SETTLEMENT<br>REFUND<br>REVERSAL<br>FEE<br>FX_CONVERSION</pre><h3>5.5 outbox_event</h3><p>Use the outbox pattern to avoid DB/Kafka inconsistency.</p><pre>CREATE TABLE outbox_event (<br>    event_id        VARCHAR(64) PRIMARY KEY,<br>    aggregate_id    VARCHAR(64) NOT NULL,<br>    event_type      VARCHAR(64) NOT NULL,<br>    payload         JSONB NOT NULL,<br>    status          VARCHAR(32) NOT NULL,<br>    created_at      TIMESTAMP NOT NULL,<br>    published_at    TIMESTAMP<br>);</pre><p>Why?</p><p>Because this prevents this problem:</p><pre>DB update succeeded<br>Kafka publish failed<br>System is now inconsistent</pre><p>Instead:</p><pre>Save payment + outbox event in same DB transaction<br>Separate publisher reads outbox and publishes to Kafka<br>Mark event as published</pre><h3>6. Kafka Topic Design</h3><pre>payment.commands<br>payment.received<br>payment.validated<br>payment.risk.approved<br>payment.risk.rejected<br>payment.fx.quoted<br>payment.routing.selected<br>payment.rail.submitted<br>payment.rail.confirmed<br>payment.settled<br>payment.failed<br>payment.reversal.requested<br>payment.reversed</pre><pre>ledger.posting.requested<br>ledger.posting.completed<br>ledger.posting.failed</pre><pre>reconciliation.started<br>reconciliation.matched<br>reconciliation.mismatched</pre><pre>payment.dlq<br>ledger.dlq</pre><p>Partition key should usually be:</p><pre>paymentId</pre><p>or:</p><pre>merchantId + paymentId</pre><p>Why?</p><p>Because all events for the same payment should be processed in order.</p><h3>7. Payment Processing Flow</h3><h3>Step 1: Client sends payment request</h3><pre>POST /payments</pre><p>The API validates basic fields and checks idempotency key.</p><h3>Step 2: Persist payment as RECEIVED</h3><pre>payment_transaction.status = RECEIVED</pre><p>Also save event in outbox:</p><pre>PaymentReceivedEvent</pre><h3>Step 3: Publish event to Kafka</h3><pre>payment.received</pre><h3>Step 4: Payment Orchestrator consumes event</h3><p>It performs:</p><pre>Validation<br>Fraud check<br>FX quote<br>Routing<br>Ledger authorization hold<br>Rail submission</pre><h3>Step 5: Ledger posting</h3><p>Before calling the external rail, the system may create an authorization or hold entry.</p><p>Example:</p><pre>Debit  Customer Available Balance<br>Credit Customer Hold Balance</pre><p>This prevents double spending.</p><h3>Step 6: Submit to external rail</h3><p>Payment rail adapter submits payment.</p><p>Possible result:</p><pre>SUCCESS<br>PENDING<br>FAILED<br>TIMEOUT<br>UNKNOWN</pre><p>The hardest status is:</p><pre>UNKNOWN</pre><p>Because the external system may have processed the payment, but we did not receive the response.</p><p>In that case, never blindly retry as a new payment. Use the same external reference ID and query the rail status.</p><h3>Step 7: Settlement</h3><p>Once confirmed:</p><pre>Debit  Customer Hold Balance<br>Credit Merchant Receivable</pre><p>Then later:</p><pre>Debit  Merchant Receivable<br>Credit Merchant Bank Account</pre><h3>Step 8: Notification</h3><p>Notify merchant/customer:</p><pre>Payment successful<br>Payment pending<br>Payment failed<br>Refund completed</pre><h3>8. Idempotency Design</h3><p>Idempotency is mandatory.</p><p>Client sends:</p><pre>Idempotency-Key: merchant123-order456</pre><p>Store this uniqueness:</p><pre>UNIQUE (merchant_id, idempotency_key)</pre><p>Behavior:</p><p>ScenarioResponseSame key, same payloadReturn original payment responseSame key, different payloadReturn 409 ConflictNew keyCreate new payment</p><p>Example:</p><pre>Merchant submits payment.<br>Network timeout happens.<br>Merchant retries same request with same idempotency key.<br>System returns same paymentId instead of creating duplicate payment.</pre><p>This protects against duplicate charges.</p><h3>9. Ledger Consistency</h3><p>The ledger must follow double-entry accounting.</p><p>For every ledger transaction:</p><pre>Total debit = Total credit</pre><p>Example payment of $100 with $2 fee:</p><pre>Debit  Customer Wallet              100<br>Credit Merchant Receivable           98<br>Credit Fee Revenue                    2</pre><p>But technically, to keep double-entry strict:</p><pre>Debit  Customer Wallet              100<br>Credit Merchant Gross Receivable     100</pre><pre>Debit  Merchant Gross Receivable       2<br>Credit Fee Revenue                    2</pre><pre>Debit  Merchant Gross Receivable      98<br>Credit Merchant Settlement Payable    98</pre><p>This gives cleaner auditability.</p><h3>10. Handling Failures</h3><h3>10.1 External rail timeout</h3><p>Problem:</p><pre>We submit payment to SWIFT.<br>Request times out.<br>We don&#39;t know whether payment succeeded.</pre><p>Solution:</p><ul><li>Store external reference ID before call</li><li>Retry status lookup, not new payment creation</li><li>Use idempotent rail reference</li><li>Mark status as UNKNOWN or PENDING_CONFIRMATION</li><li>Reconciliation process resolves it later</li></ul><h3>10.2 Kafka consumer failure</h3><p>Use:</p><ul><li>Consumer offset commit after DB transaction</li><li>Idempotent consumer table</li><li>Retry with exponential backoff</li><li>DLQ after max retry</li></ul><p>Example table:</p><pre>CREATE TABLE processed_event (<br>    event_id VARCHAR(64) PRIMARY KEY,<br>    processed_at TIMESTAMP NOT NULL<br>);</pre><p>Before processing an event:</p><pre>Check if event_id already processed.<br>If yes, skip.<br>If no, process and insert event_id.</pre><h3>10.3 Ledger posting failure</h3><p>Ledger posting should be atomic.</p><p>Use DB transaction:</p><pre>Insert ledger_transaction<br>Insert debit entries<br>Insert credit entries<br>Validate debit == credit<br>Commit</pre><p>If validation fails, rollback.</p><h3>10.4 Duplicate messages</h3><p>Kafka can deliver messages more than once.</p><p>So consumers must be idempotent.</p><p>Rules:</p><pre>Do not rely only on Kafka exactly-once.<br>Design application-level idempotency.<br>Use event_id, payment_id, transaction_id uniqueness.</pre><h3>10.5 Dead Letter Queue</h3><p>After retry limit:</p><pre>payment.dlq<br>ledger.dlq<br>reconciliation.dlq</pre><p>DLQ message should contain:</p><pre>{<br>  &quot;eventId&quot;: &quot;EVT-123&quot;,<br>  &quot;paymentId&quot;: &quot;PAY-10001&quot;,<br>  &quot;failureReason&quot;: &quot;Ledger posting failed&quot;,<br>  &quot;retryCount&quot;: 5,<br>  &quot;lastError&quot;: &quot;DB timeout&quot;,<br>  &quot;timestamp&quot;: &quot;2026-07-11T10:15:30Z&quot;<br>}</pre><h3>11. Reconciliation Design</h3><p>Reconciliation compares internal records with external payment rail reports.</p><p>Sources:</p><pre>Internal payment table<br>Internal ledger table<br>External rail settlement file<br>Bank statement<br>Merchant settlement report</pre><p>Types of reconciliation:</p><pre>Payment reconciliation<br>Ledger reconciliation<br>Bank reconciliation<br>Merchant settlement reconciliation<br>FX reconciliation<br>Fee reconciliation</pre><p>Example mismatch:</p><pre>Internal system says payment SETTLED for $100.<br>External bank file says $99 settled.</pre><p>Actions:</p><pre>Mark as MISMATCH<br>Create reconciliation case<br>Generate adjustment ledger entry if approved<br>Alert operations team</pre><p>Reconciliation table:</p><pre>CREATE TABLE reconciliation_result (<br>    reconciliation_id VARCHAR(64) PRIMARY KEY,<br>    payment_id        VARCHAR(64),<br>    external_reference_id VARCHAR(128),<br>    internal_amount   DECIMAL(19,4),<br>    external_amount   DECIMAL(19,4),<br>    status            VARCHAR(32),<br>    mismatch_reason   TEXT,<br>    created_at        TIMESTAMP NOT NULL<br>);</pre><h3>12. Global / Multi-Region Design</h3><p>For global payments, design must handle:</p><ul><li>Multiple countries</li><li>Multiple currencies</li><li>Multiple payment rails</li><li>Data residency</li><li>Regional failover</li><li>Low latency</li><li>Compliance</li></ul><p>Possible architecture:</p><pre>US Region<br> - Payment API<br> - Payment Orchestrator<br> - Ledger DB shard<br> - Kafka cluster</pre><pre>EU Region<br> - Payment API<br> - Payment Orchestrator<br> - Ledger DB shard<br> - Kafka cluster</pre><pre>APAC Region<br> - Payment API<br> - Payment Orchestrator<br> - Ledger DB shard<br> - Kafka cluster</pre><p>Routing strategy:</p><pre>Customer in US -&gt; US region<br>Customer in EU -&gt; EU region<br>Customer in India -&gt; APAC region</pre><p>Important:</p><p>For ledger consistency, avoid active-active writes to the same ledger account across regions unless using a globally consistent database.</p><p>Better approach:</p><pre>Partition ledger by region/account/currency.<br>Each account has one write leader region.<br>Replicate read-only copies globally.</pre><h3>13. Scaling Strategy</h3><h3>Application scaling</h3><ul><li>Stateless services</li><li>Horizontal autoscaling with Kubernetes</li><li>Kafka consumer groups</li><li>Partition by paymentId or accountId</li><li>Separate read and write paths</li></ul><h3>Database scaling</h3><ul><li>Partition by region</li><li>Partition by merchantId</li><li>Partition by accountId</li><li>Use read replicas for queries</li><li>Keep ledger writes strongly consistent</li></ul><h3>Kafka scaling</h3><ul><li>Increase partitions</li><li>Use consumer groups</li><li>Use compacted topics for latest status if needed</li><li>Use retention for replay and audit</li></ul><h3>14. Security and Compliance</h3><p>Security requirements:</p><ul><li>OAuth2 / JWT authentication</li><li>mTLS between services</li><li>Encryption at rest</li><li>Encryption in transit</li><li>Tokenization for sensitive account data</li><li>PII masking in logs</li><li>Role-based access control</li><li>Audit logs for every admin action</li><li>Secrets stored in Vault or cloud secret manager</li></ul><p>Payment compliance:</p><ul><li>PCI DSS for card data</li><li>AML monitoring</li><li>Sanctions screening</li><li>Regional data privacy rules</li><li>Strong audit trail</li></ul><h3>15. Observability</h3><p>Use:</p><ul><li>Centralized logs</li><li>Metrics</li><li>Distributed tracing</li><li>Audit events</li><li>Business dashboards</li></ul><p>Important metrics:</p><pre>payment_success_rate<br>payment_failure_rate<br>payment_latency_p95<br>payment_latency_p99<br>ledger_posting_failure_count<br>kafka_consumer_lag<br>dlq_message_count<br>rail_timeout_count<br>reconciliation_mismatch_count<br>duplicate_payment_attempt_count</pre><p>Trace should follow:</p><pre>API Gateway<br> -&gt; Payment Orchestrator<br> -&gt; Validation Service<br> -&gt; Fraud Service<br> -&gt; FX Service<br> -&gt; Ledger Service<br> -&gt; Rail Adapter<br> -&gt; Notification Service</pre><p>Every log should contain:</p><pre>correlationId<br>paymentId<br>merchantId<br>eventId<br>externalReferenceId</pre><h3>16. Availability and Reliability</h3><p>Design choices:</p><pre>Multi-AZ deployment<br>Regional failover<br>Kafka replication<br>Database backups<br>Point-in-time recovery<br>Circuit breakers<br>Bulkheads<br>Timeouts<br>Retries with backoff<br>DLQ<br>Graceful degradation</pre><p>For example:</p><p>If Fraud Service is down:</p><pre>High-risk payments -&gt; hold for manual review<br>Low-risk payments -&gt; process only if business allows</pre><p>If Notification Service is down:</p><pre>Do not fail the payment.<br>Queue notification and retry later.</pre><p>If Ledger Service is down:</p><pre>Stop payment processing.<br>Never move money without ledger posting.</pre><h3>17. Key Trade-Offs</h3><p>DecisionTrade-offAsync processingBetter scale, but client does not get instant final statusStrong ledger consistencySlower writes, but safer money movementKafka event-driven designMore scalable, but requires idempotent consumersRegional partitioningBetter latency, but cross-region payments become complexOutbox patternMore reliable, but adds operational complexityDouble-entry ledgerMore complex schema, but excellent auditability</p><h3>18. Interview-Ready Summary</h3><p>You can explain the design like this:</p><blockquote><em>I would design the payment system as an event-driven architecture where the Payment Orchestrator manages the transaction lifecycle and the Ledger Service acts as the source of truth. The payment API accepts requests with an idempotency key, stores the transaction in a relational database, and publishes events through Kafka using the outbox pattern. Each payment goes through validation, fraud checks, FX conversion, routing, external rail submission, ledger posting, settlement, notification, and reconciliation.</em></blockquote><blockquote><em>For the ledger, I would use double-entry accounting with immutable ledger entries, ensuring every debit has a matching credit. Kafka consumers would be idempotent because duplicate events are possible. For failures, I would use retries with exponential backoff, DLQs, circuit breakers, and reconciliation jobs to handle unknown or mismatched external payment states.</em></blockquote><blockquote><em>Globally, I would partition by region, currency, account, or merchant, while ensuring each ledger account has a single write owner to avoid consistency issues. The system would be observable through distributed tracing, metrics, audit logs, and reconciliation dashboards.</em></blockquote><h3>19. Simple Final Diagram</h3><pre>+----------------+<br>Client / Merchant -&gt;|  API Gateway   |<br>                    +--------+-------+<br>                             |<br>                             v<br>                    +--------------------+<br>                    | Payment Service    |<br>                    | Idempotency Check  |<br>                    +--------+-----------+<br>                             |<br>                             v<br>                    +--------------------+<br>                    | Outbox + Payment DB|<br>                    +--------+-----------+<br>                             |<br>                             v<br>                         Kafka<br>                             |<br>        +--------------------+--------------------+<br>        |                    |                    |<br>        v                    v                    v<br>Validation Service     Fraud Service        FX Service<br>        |                    |                    |<br>        +--------------------+--------------------+<br>                             |<br>                             v<br>                    +--------------------+<br>                    | Routing Service    |<br>                    +--------+-----------+<br>                             |<br>                             v<br>                    +--------------------+<br>                    | Ledger Service     |<br>                    +--------+-----------+<br>                             |<br>                             v<br>                    +--------------------+<br>                    | Rail Adapter       |<br>                    | ACH/Wire/SWIFT/RTP |<br>                    +--------+-----------+<br>                             |<br>                             v<br>                    +--------------------+<br>                    | Reconciliation     |<br>                    +--------------------+</pre><p>The strongest interview point is this:</p><blockquote><strong><em>Payment processing can be eventually consistent, but ledger posting must be strongly consistent, immutable, idempotent, and auditable.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa0410114ee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Case study / System Design Round for Banking Tech Giant]]></title>
            <link>https://dildeepak.medium.com/case-study-system-design-round-for-banking-tech-giant-012928eb256e?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/012928eb256e</guid>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 10:17:02 GMT</pubDate>
            <atom:updated>2026-07-09T10:20:48.750Z</atom:updated>
            <content:encoded><![CDATA[<h3>Case study for Banking Tech Giant</h3><h3>Case Study: Payment Transaction Validation and Duplicate Prevention System</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*Xmv4kTRkEPiyD9c8JjDGLw.jpeg" /></figure><h3>Role Context</h3><p>You are joining the Global Payment Network team as a Senior Lead Software Engineer. The platform processes payment transactions from multiple merchants, card networks, and internal services. Recently, business teams have reported that some transactions are failing, some are duplicated, and some invalid transactions are reaching downstream settlement systems.</p><p>Your task is to design and partially code a transaction validation component that can detect invalid transactions, prevent duplicate processing, and produce auditable validation results.</p><h3>1. Business Scenario</h3><p>Bank receives payment authorization events from multiple merchants. Each merchant submits transactions through APIs or event streams. Due to retries, network timeouts, and merchant integration issues, the system sometimes receives the same transaction more than once.</p><p>The business has observed the following issues:</p><ol><li>Duplicate transactions are sometimes processed twice.</li><li>Transactions with invalid amounts are reaching downstream systems.</li><li>Inactive merchants are still submitting payment requests.</li><li>Some transactions are missing required fields.</li><li>The operations team has limited visibility into why a transaction was declined.</li><li>Reconciliation between internal records and external network settlement files is becoming difficult.</li></ol><p>The goal is to build a validation layer that improves correctness, auditability, and operational visibility.</p><h3>2. Problem Statement</h3><p>Design and implement a Java-based transaction validation service.</p><p>The service should process a list of incoming payment transactions and return a validation result for each transaction.</p><p>A transaction should be approved only if:</p><ol><li>The transaction ID is not duplicated.</li><li>The amount is greater than zero.</li><li>The currency is supported.</li><li>The merchant is active.</li><li>The account/card is active.</li><li>The timestamp is present.</li><li>Required fields are not missing.</li></ol><p>For every declined transaction, the system should return a clear reason code.</p><h3>3. Sample Input</h3><pre>Supported currencies:<br>USD, CAD</pre><pre>Active merchants:<br>M100, M200</pre><pre>Active accounts:<br>A100, A200, A300</pre><pre>Incoming transactions:</pre><pre>1. transactionId=T001, accountId=A100, merchantId=M100, amount=120.50, currency=USD<br>2. transactionId=T002, accountId=A200, merchantId=M100, amount=0.00, currency=USD<br>3. transactionId=T003, accountId=A300, merchantId=M999, amount=75.00, currency=USD<br>4. transactionId=T001, accountId=A100, merchantId=M100, amount=120.50, currency=USD<br>5. transactionId=T004, accountId=A999, merchantId=M200, amount=20.00, currency=CAD<br>6. transactionId=T005, accountId=A100, merchantId=M200, amount=10.00, currency=EUR</pre><h3>4. Expected Output</h3><pre>T001 -&gt; APPROVED, VALID<br>T002 -&gt; DECLINED, INVALID_AMOUNT<br>T003 -&gt; DECLINED, INACTIVE_MERCHANT<br>T001 -&gt; DECLINED, DUPLICATE_TRANSACTION<br>T004 -&gt; DECLINED, INACTIVE_ACCOUNT<br>T005 -&gt; DECLINED, UNSUPPORTED_CURRENCY</pre><p><a href="https://dildeepak.medium.com/kubernetes-interview-questions-for-experienced-you-shouldnt-attend-any-exam-without-them-755696861b30">Kubernetes Interview Questions for Experienced — You shouldn’t attend any exam without them</a></p><h3>5. Candidate Expectations</h3><p>As a Senior Lead candidate, you are expected to do more than write working code.</p><p>You should demonstrate:</p><ol><li>Clear requirement clarification.</li><li>Clean Java coding style.</li><li>Correct use of data structures.</li><li>Awareness of payment-domain risks.</li><li>Understanding of idempotency.</li><li>Production-readiness thinking.</li><li>Audit and reconciliation awareness.</li><li>Ability to communicate trade-offs.</li></ol><h3>6. Clarifying Questions to Ask</h3><p>Before coding, ask questions like:</p><ol><li>Is transactionId globally unique across all merchants?</li><li>Should duplicates be rejected or should we return the previously computed result?</li><li>Are retries expected from merchants or from our internal Kafka consumers?</li><li>Should amount be represented with decimal precision?</li><li>Should currency validation be case-sensitive?</li><li>Are timestamps always in UTC?</li><li>Do we need to audit both approved and declined transactions?</li><li>Should validation stop at the first failure or return all failure reasons?</li><li>Is this an in-memory coding exercise or should I discuss distributed production behavior?</li></ol><p>A strong opening statement:</p><pre>Before I code, I want to clarify the validation rules and edge cases. Since this is a payment system, I will also consider idempotency, auditability, retry behavior, and reconciliation. For the coding exercise, I will implement an in-memory solution first, then explain how I would make it production-ready in a distributed environment.</pre><h3>7. Data Model</h3><pre>import java.math.BigDecimal;<br>import java.time.Instant;</pre><pre>public record Transaction(<br>        String transactionId,<br>        String accountId,<br>        String merchantId,<br>        BigDecimal amount,<br>        String currency,<br>        Instant timestamp<br>) {}</pre><h3>8. Validation Result Model</h3><pre>public enum TransactionStatus {<br>    APPROVED,<br>    DECLINED<br>}</pre><pre>public enum ReasonCode {<br>    VALID,<br>    MISSING_REQUIRED_FIELD,<br>    DUPLICATE_TRANSACTION,<br>    INVALID_AMOUNT,<br>    UNSUPPORTED_CURRENCY,<br>    INACTIVE_MERCHANT,<br>    INACTIVE_ACCOUNT,<br>    MISSING_TIMESTAMP<br>}</pre><pre>public record ValidationResult(<br>        String transactionId,<br>        TransactionStatus status,<br>        ReasonCode reasonCode<br>) {}</pre><h3>9. Java Solution</h3><pre>import java.math.BigDecimal;<br>import java.time.Instant;<br>import java.util.*;</pre><pre>public class PaymentValidationService {</pre><pre>    public List&lt;ValidationResult&gt; validateTransactions(<br>            List&lt;Transaction&gt; transactions,<br>            Set&lt;String&gt; activeAccounts,<br>            Set&lt;String&gt; activeMerchants,<br>            Set&lt;String&gt; supportedCurrencies<br>    ) {<br>        List&lt;ValidationResult&gt; results = new ArrayList&lt;&gt;();<br>        Set&lt;String&gt; processedTransactionIds = new HashSet&lt;&gt;();</pre><pre>        for (Transaction transaction : transactions) {<br>            ValidationResult result = validateTransaction(<br>                    transaction,<br>                    processedTransactionIds,<br>                    activeAccounts,<br>                    activeMerchants,<br>                    supportedCurrencies<br>            );</pre><pre>            results.add(result);<br>        }</pre><pre>        return results;<br>    }</pre><pre>    private ValidationResult validateTransaction(<br>            Transaction transaction,<br>            Set&lt;String&gt; processedTransactionIds,<br>            Set&lt;String&gt; activeAccounts,<br>            Set&lt;String&gt; activeMerchants,<br>            Set&lt;String&gt; supportedCurrencies<br>    ) {<br>        if (transaction == null) {<br>            return new ValidationResult(null, TransactionStatus.DECLINED, ReasonCode.MISSING_REQUIRED_FIELD);<br>        }</pre><pre>        if (isBlank(transaction.transactionId())<br>                || isBlank(transaction.accountId())<br>                || isBlank(transaction.merchantId())<br>                || isBlank(transaction.currency())) {<br>            return decline(transaction.transactionId(), ReasonCode.MISSING_REQUIRED_FIELD);<br>        }</pre><pre>        if (!processedTransactionIds.add(transaction.transactionId())) {<br>            return decline(transaction.transactionId(), ReasonCode.DUPLICATE_TRANSACTION);<br>        }</pre><pre>        if (transaction.amount() == null || transaction.amount().compareTo(BigDecimal.ZERO) &lt;= 0) {<br>            return decline(transaction.transactionId(), ReasonCode.INVALID_AMOUNT);<br>        }</pre><pre>        if (!supportedCurrencies.contains(transaction.currency())) {<br>            return decline(transaction.transactionId(), ReasonCode.UNSUPPORTED_CURRENCY);<br>        }</pre><pre>        if (!activeMerchants.contains(transaction.merchantId())) {<br>            return decline(transaction.transactionId(), ReasonCode.INACTIVE_MERCHANT);<br>        }</pre><pre>        if (!activeAccounts.contains(transaction.accountId())) {<br>            return decline(transaction.transactionId(), ReasonCode.INACTIVE_ACCOUNT);<br>        }</pre><pre>        if (transaction.timestamp() == null) {<br>            return decline(transaction.transactionId(), ReasonCode.MISSING_TIMESTAMP);<br>        }</pre><pre>        return new ValidationResult(<br>                transaction.transactionId(),<br>                TransactionStatus.APPROVED,<br>                ReasonCode.VALID<br>        );<br>    }</pre><pre>    private ValidationResult decline(String transactionId, ReasonCode reasonCode) {<br>        return new ValidationResult(transactionId, TransactionStatus.DECLINED, reasonCode);<br>    }</pre><pre>    private boolean isBlank(String value) {<br>        return value == null || value.trim().isEmpty();<br>    }<br>}</pre><h3>10. Why This Solution Works</h3><p>This solution uses a HashSet to track processed transaction IDs.</p><p>The validation is done in one pass through the list of transactions.</p><p>Time complexity:</p><pre>O(n)</pre><p>where n is the number of transactions.</p><p>Space complexity:</p><pre>O(n)</pre><p>because transaction IDs are stored for duplicate detection.</p><p>The solution is efficient for an interview coding problem because each transaction is processed once and lookup operations are constant time on average.</p><p><a href="https://dildeepak.medium.com/kafka-interview-question-for-experienced-professional-15202727bee0">Kafka Interview Question — For Experienced Professional</a></p><h3>11. Senior-Level Discussion</h3><p>After completing the code, you should explain how you would improve this for production.</p><p>A strong answer:</p><pre>This in-memory solution works for the coding exercise, but in production, this service would run on multiple pods or containers. A local HashSet would not be enough because duplicate messages could be processed by different instances.</pre><pre>For production, I would store the idempotency key or transaction ID in a shared persistent store such as a database table or Redis. The insert operation should be atomic, so only one service instance can process a transaction successfully.</pre><pre>I would also store the validation result, reason code, timestamp, correlation ID, source system, and service version in an audit table. This helps with debugging, compliance, customer support, and reconciliation.</pre><h3>12. Production Architecture</h3><p>A production-ready flow could look like this:</p><pre>Merchant API / Kafka Topic<br>        |<br>        v<br>Payment Validation Service<br>        |<br>        |-- Check idempotency store<br>        |-- Validate merchant/account/currency/amount<br>        |-- Write audit event<br>        |-- Publish validation result<br>        |<br>        v<br>Approved Topic / Declined Topic / DLQ<br>        |<br>        v<br>Authorization / Ledger / Reconciliation Systems</pre><h3>13. Idempotency Design</h3><p>In production, use an idempotency table:</p><pre>CREATE TABLE payment_idempotency (<br>    id BIGINT PRIMARY KEY AUTO_INCREMENT,<br>    transaction_id VARCHAR(100) NOT NULL,<br>    merchant_id VARCHAR(100) NOT NULL,<br>    idempotency_key VARCHAR(255) NOT NULL UNIQUE,<br>    status VARCHAR(50) NOT NULL,<br>    response_code VARCHAR(100),<br>    created_at TIMESTAMP NOT NULL,<br>    updated_at TIMESTAMP NOT NULL<br>);</pre><p>The idempotency key could be:</p><pre>merchantId + transactionId</pre><p>or, if transaction ID is not reliable:</p><pre>merchantId + accountId + amount + currency + timestamp</pre><p>Senior-level point:</p><pre>I would prefer a stable transaction ID or client-provided idempotency key. Hashing business fields can be risky because two legitimate transactions may look similar.</pre><h3>14. Audit Table Design</h3><pre>CREATE TABLE payment_validation_audit (<br>    audit_id BIGINT PRIMARY KEY AUTO_INCREMENT,<br>    transaction_id VARCHAR(100),<br>    merchant_id VARCHAR(100),<br>    account_id VARCHAR(100),<br>    amount DECIMAL(18, 2),<br>    currency VARCHAR(10),<br>    validation_status VARCHAR(50),<br>    reason_code VARCHAR(100),<br>    correlation_id VARCHAR(100),<br>    source_system VARCHAR(100),<br>    created_at TIMESTAMP NOT NULL<br>);</pre><p>Why this matters:</p><pre>For payment systems, even declined and duplicate transactions should be audited. This helps operations teams answer why a payment failed, whether the customer was charged, and whether the transaction reached downstream systems.</pre><h3>15. Kafka and DLQ Design</h3><p>Kafka topics:</p><pre>payment-transaction-received<br>payment-transaction-approved<br>payment-transaction-declined<br>payment-transaction-duplicate<br>payment-validation-dlq</pre><p>Retry strategy:</p><pre>Transient error:<br>Retry with exponential backoff.</pre><pre>Permanent validation error:<br>Do not retry forever. Publish to declined topic with reason code.</pre><pre>Poison message:<br>Send to DLQ with original payload and error details.</pre><p>Senior-level explanation:</p><pre>Since Kafka provides at-least-once delivery, the consumer must be idempotent. I would commit the Kafka offset only after the validation result and audit record are successfully written. If processing fails before commit, Kafka may redeliver the event, but the idempotency check prevents duplicate processing.</pre><p><a href="https://dildeepak.medium.com/spring-core-and-spring-boot-interview-questions-for-experienced-professional-75b18da2a176">Spring Core and Spring Boot Interview Questions for Experienced Professional</a></p><h3>16. Reconciliation Design</h3><p>A reconciliation process compares internal transaction records with external network settlement records.</p><p>Example checks:</p><ol><li>Transaction exists internally but not externally.</li><li>Transaction exists externally but not internally.</li><li>Amount mismatch.</li><li>Currency mismatch.</li><li>Status mismatch.</li><li>Settlement date mismatch.</li></ol><p>Reconciliation table:</p><pre>CREATE TABLE payment_reconciliation_exception (<br>    exception_id BIGINT PRIMARY KEY AUTO_INCREMENT,<br>    transaction_id VARCHAR(100),<br>    exception_type VARCHAR(100),<br>    internal_status VARCHAR(50),<br>    external_status VARCHAR(50),<br>    internal_amount DECIMAL(18, 2),<br>    external_amount DECIMAL(18, 2),<br>    created_at TIMESTAMP NOT NULL<br>);</pre><p>Senior-level explanation:</p><pre>I would run reconciliation as a scheduled batch or event-driven process. Any mismatch would be stored as an exception record and surfaced through dashboards or alerts. This is important because payment correctness is not only about real-time approval; it is also about settlement accuracy.</pre><h3>17. Edge Cases to Mention</h3><p>You should proactively mention these edge cases:</p><ol><li>Duplicate transaction ID with different amount.</li><li>Same transaction received from two different merchants.</li><li>Missing account ID.</li><li>Negative amount.</li><li>Zero amount.</li><li>Unsupported currency.</li><li>Lowercase currency value like usd.</li><li>Null timestamp.</li><li>Future timestamp.</li><li>Inactive merchant.</li><li>Inactive account.</li><li>Large transaction volume.</li><li>Concurrent processing across multiple service instances.</li><li>Kafka redelivery.</li><li>Database timeout after payment approval but before audit write.</li></ol><h3>18. Possible Follow-Up Questions and Strong Answers</h3><h3>Question 1: Why did you use BigDecimal instead of double?</h3><p>Answer:</p><pre>Money should not be represented using double because double can introduce floating-point precision errors. BigDecimal gives exact decimal representation, which is important for payment, ledger, and settlement systems.</pre><h3>Question 2: Why is HashSet useful here?</h3><p>Answer:</p><pre>HashSet gives average O(1) lookup and insertion. That makes it efficient for detecting duplicate transaction IDs while processing a large list of transactions.</pre><h3>Question 3: Is your solution thread-safe?</h3><p>Answer:</p><pre>The current in-memory solution is not designed for concurrent access. For the coding exercise, the set is local to the method, so it is safe within one execution. But in production, duplicate detection should be handled through a shared atomic store like a database unique constraint or Redis SETNX operation.</pre><h3>Question 4: How would you handle duplicate transaction IDs with different amounts?</h3><p>Answer:</p><pre>That is suspicious. I would not silently treat it as a normal duplicate. I would compare the incoming payload with the original transaction. If the transaction ID is same but amount or merchant is different, I would mark it as a potential integrity issue and send it to an exception queue or fraud/risk review process.</pre><h3>Question 5: What happens if audit write fails?</h3><p>Answer:</p><pre>For a payment system, audit failure is serious. I would try to keep validation result and audit write in the same transaction boundary where possible. If that is not possible, I would use an outbox pattern so the audit event is reliably persisted and published later.</pre><h3>Question 6: How would you make this scalable?</h3><p>Answer:</p><pre>I would keep the validation service stateless and horizontally scalable. Shared state like idempotency, merchant status, account status, and audit records should be stored externally. Kafka partitions can be keyed by transaction ID or account ID depending on ordering requirements. Metrics and tracing should be added for visibility.</pre><h3>19. Evaluation Criteria</h3><p>The interviewer may evaluate you on:</p><ol><li>Did you clarify requirements before coding?</li><li>Did you choose the right data structures?</li><li>Did you write clean Java?</li><li>Did you handle edge cases?</li><li>Did you explain time and space complexity?</li><li>Did you understand payment-domain concerns?</li><li>Did you discuss idempotency?</li><li>Did you discuss auditability?</li><li>Did you discuss retry and DLQ?</li><li>Did you show senior-level production thinking?</li></ol><p><a href="https://dildeepak.medium.com/top-30-spring-boot-interview-questions-with-answers-for-experienced-java-developer-764e9172239d">Top 30 Spring Boot Interview Questions with Answers for Experienced Java Developer</a></p><h3>20. Final Interview Summary</h3><p>A strong final summary would be:</p><pre>I implemented the validation logic using a simple O(n) approach with a HashSet for duplicate detection and constant-time lookups for account, merchant, and currency validation.</pre><pre>For production, I would not rely on in-memory duplicate detection. I would use a persistent idempotency store with atomic writes, maintain an audit table for every validation decision, publish approved and declined events to separate Kafka topics, and send poison messages to DLQ.</pre><pre>I would also add reconciliation to compare internal transaction records with external network settlement files. This ensures not only real-time correctness but also settlement accuracy, which is critical in a payment network.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=012928eb256e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Interview Questions for Experienced — You shouldn’t attend any exam without them]]></title>
            <link>https://dildeepak.medium.com/kubernetes-interview-questions-for-experienced-you-shouldnt-attend-any-exam-without-them-755696861b30?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/755696861b30</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 07:35:27 GMT</pubDate>
            <atom:updated>2026-07-09T10:35:10.085Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are preparing for any upcoming <strong>Sr. Lead Software Engineer / Staff Engineer </strong>interviews, Kubernetes questions will likely focus on <strong>microservices deployment, reliability, scaling, troubleshooting, security, and production operations</strong> rather than plain definitions.</p><p>I have tried to prepare a list of important questions including situation based, real time. (At the last added few more questions to prepare for the same. If you have time and want to prepare in length, you should prepare them as well )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*Py3xsjAAgf11AKmt8u3kOg.jpeg" /></figure><h3>1. How to explain Kubernetes in an interview</h3><p>A good senior-level answer:</p><blockquote><em>Kubernetes is a container orchestration platform used to deploy, scale, manage, and recover containerized applications. In a microservices environment, instead of manually running Docker containers, Kubernetes manages Pods, services, configuration, secrets, networking, health checks, rolling deployments, auto-scaling, and self-healing.</em></blockquote><blockquote><em>In my projects, Kubernetes is useful for running Spring Boot microservices reliably. Each service runs as a Deployment, exposed internally through a Service, configured using ConfigMaps and Secrets, monitored through logs and metrics, and scaled horizontally based on CPU, memory, or traffic. For payment systems, Kubernetes helps with high availability, controlled releases, rollback, fault isolation, and zero-downtime deployments.</em></blockquote><h3>2. Kubernetes architecture questions</h3><h3>Q1. What are the main components of Kubernetes?</h3><p><strong>Answer:</strong></p><p>Kubernetes has two main parts: the <strong>control plane</strong> and <strong>worker nodes</strong>.</p><p>The control plane manages the cluster. It includes:</p><p>ComponentPurposeAPI ServerEntry point for all Kubernetes operationsSchedulerDecides which node should run a PodController ManagerMaintains desired stateetcdStores cluster state/configuration</p><p>Worker nodes actually run the applications. They include:</p><p>ComponentPurposekubeletAgent running on each nodekube-proxyHandles service networkingContainer runtimeRuns containers, such as containerd</p><p>Senior-level explanation:</p><blockquote><em>Kubernetes follows a desired-state model. We declare what we want, like three replicas of a payment service, and Kubernetes continuously works to maintain that state. If a Pod crashes, Kubernetes creates a replacement automatically.</em></blockquote><h3>Q2. What happens when you apply a deployment YAML?</h3><p>Example command:</p><pre>kubectl apply -f payment-service-deployment.yaml</pre><p><strong>Answer:</strong></p><p>When we apply a YAML file, the request goes to the Kubernetes API Server. The API Server validates the request and stores the desired state in etcd. Then the Deployment controller creates or updates the ReplicaSet. The ReplicaSet ensures the required number of Pods are running. The Scheduler assigns the Pods to worker nodes. Finally, kubelet on each node pulls the Docker image and starts the container.</p><p>Strong interview version:</p><blockquote><em>In short, Kubernetes compares current state with desired state and continuously reconciles the difference.</em></blockquote><h3>3. Pod, Deployment, ReplicaSet</h3><h3>Q3. What is a Pod?</h3><p><strong>Answer:</strong></p><p>A Pod is the smallest deployable unit in Kubernetes. It usually contains one application container, although it can contain multiple tightly coupled containers.</p><p>Example:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: payment-service-pod<br>spec:<br>  containers:<br>    - name: payment-service<br>      image: payment-service:1.0<br>      ports:<br>        - containerPort: 8080</pre><p>Interview explanation:</p><blockquote><em>In real production systems, we usually do not create standalone Pods directly. We use Deployments, which manage ReplicaSets and Pods.</em></blockquote><h3>Q4. What is a Deployment?</h3><p><strong>Answer:</strong></p><p>A Deployment manages application rollout, scaling, and self-healing. It ensures that the desired number of Pods are always running.</p><p>Example:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: payment-service<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: payment-service<br>  template:<br>    metadata:<br>      labels:<br>        app: payment-service<br>    spec:<br>      containers:<br>        - name: payment-service<br>          image: payment-service:1.0<br>          ports:<br>            - containerPort: 8080</pre><p>Good interview answer:</p><blockquote><em>For a payment microservice, I would run it as a Deployment with multiple replicas so that if one Pod fails, traffic can still be served by the remaining Pods.</em></blockquote><h3>Q5. What is the difference between Pod, ReplicaSet, and Deployment?</h3><p>ConceptPurposePodRuns one or more containersReplicaSetMaintains a fixed number of Pod replicasDeploymentManages ReplicaSet, rollout, rollback, and scaling</p><p>Simple answer:</p><blockquote><em>Pod runs the container, ReplicaSet keeps the required number of Pods alive, and Deployment manages versioning, rollout, rollback, and lifecycle.</em></blockquote><h3>4. Service, Ingress, Networking</h3><h3>Q6. Why do we need a Kubernetes Service?</h3><p><strong>Answer:</strong></p><p>Pods are temporary and can be recreated anytime. Their IP addresses can change. A Service provides a stable network endpoint to access a group of Pods.</p><p>Example:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: payment-service<br>spec:<br>  selector:<br>    app: payment-service<br>  ports:<br>    - port: 80<br>      targetPort: 8080<br>  type: ClusterIP</pre><p>Interview answer:</p><blockquote><em>In microservices, one service should not directly call a Pod IP. It should call the Kubernetes Service name, such as </em><em>http://payment-service, because Kubernetes handles load balancing to healthy Pods.</em></blockquote><p><a href="https://dildeepak.medium.com/kafka-interview-question-for-experienced-professional-15202727bee0">Kafka Interview Question — For Experienced Professional</a></p><h3>Q7. Types of Kubernetes Services?</h3><p>Service TypeUsageClusterIPInternal communication inside clusterNodePortExposes service on node portLoadBalancerExposes service externally through cloud load balancerExternalNameMaps service to external DNS name</p><p>For interview:</p><blockquote><em>For internal microservice-to-microservice communication, I would use ClusterIP. For external API traffic, I would usually use Ingress or LoadBalancer depending on architecture.</em></blockquote><h3>Q8. What is Ingress?</h3><p><strong>Answer:</strong></p><p>Ingress manages external HTTP/HTTPS access to services inside the cluster. It supports routing, TLS termination, path-based routing, and host-based routing.</p><p>Example:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: payment-ingress<br>spec:<br>  rules:<br>    - host: payments.example.com<br>      http:<br>        paths:<br>          - path: /payments<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: payment-service<br>                port:<br>                  number: 80</pre><p>Interview answer:</p><blockquote><em>Ingress is useful when multiple APIs need to be exposed through a single external endpoint. For example, </em><em>/payments, </em><em>/accounts, and </em><em>/transactions can route to different backend services.</em></blockquote><h3>5. ConfigMap and Secret</h3><h3>Q9. What is ConfigMap?</h3><p><strong>Answer:</strong></p><p>ConfigMap stores non-sensitive configuration outside the application image.</p><p>Example:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: payment-config<br>data:<br>  SPRING_PROFILES_ACTIVE: prod<br>  KAFKA_TOPIC: payment-events</pre><p>Usage in Deployment:</p><pre>envFrom:<br>  - configMapRef:<br>      name: payment-config</pre><p>Interview answer:</p><blockquote><em>ConfigMaps help separate configuration from code. The same Docker image can be promoted across dev, QA, and production with different environment-specific configurations.</em></blockquote><h3>Q10. What is Secret?</h3><p><strong>Answer:</strong></p><p>Secret stores sensitive information such as passwords, tokens, and API keys.</p><p>Example:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: payment-secret<br>type: Opaque<br>data:<br>  DB_PASSWORD: cGFzc3dvcmQ=</pre><p>Interview note:</p><blockquote><em>Kubernetes Secrets are base64 encoded, not automatically encrypted unless encryption at rest is enabled. In production, I would integrate with cloud secret managers such as AWS Secrets Manager, GCP Secret Manager, or HashiCorp Vault.</em></blockquote><h3>6. Health checks: readiness and liveness probes</h3><h3>Q11. What is a liveness probe?</h3><p><strong>Answer:</strong></p><p>A liveness probe checks whether the application is still alive. If it fails, Kubernetes restarts the container.</p><p>Example:</p><pre>livenessProbe:<br>  httpGet:<br>    path: /actuator/health/liveness<br>    port: 8080<br>  initialDelaySeconds: 30<br>  periodSeconds: 10</pre><h3>Q12. What is a readiness probe?</h3><p><strong>Answer:</strong></p><p>A readiness probe checks whether the application is ready to receive traffic. If it fails, Kubernetes removes that Pod from the Service endpoint list.</p><p>Example:</p><pre>readinessProbe:<br>  httpGet:<br>    path: /actuator/health/readiness<br>    port: 8080<br>  initialDelaySeconds: 20<br>  periodSeconds: 10</pre><p>Strong senior answer:</p><blockquote><em>For payment services, readiness is very important. A Pod may be running but not ready if it cannot connect to the database, Kafka, or downstream service. In that case, Kubernetes should not send traffic to it.</em></blockquote><p><a href="https://dildeepak.medium.com/spring-core-and-spring-boot-interview-questions-for-experienced-professional-75b18da2a176">Spring Core and Spring Boot Interview Questions for Experienced Professional</a></p><h3>Q13. Difference between liveness and readiness?</h3><p>ProbePurposeFailure behaviorLivenessIs app alive?Restarts containerReadinessCan app receive traffic?Removes from trafficStartupHas app started?Delays liveness/readiness checks</p><p>Interview example:</p><blockquote><em>If my Spring Boot app is stuck due to deadlock, liveness should fail and restart the container. If the app is healthy but database connection is not ready, readiness should fail so traffic is not routed to that Pod.</em></blockquote><h3>7. Scaling and high availability</h3><h3>Q14. How do you scale an application in Kubernetes?</h3><p>Manually:</p><pre>kubectl scale deployment payment-service --replicas=5</pre><p>Using YAML:</p><pre>spec:<br>  replicas: 5</pre><p>Using HPA:</p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: payment-service-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: payment-service<br>  minReplicas: 3<br>  maxReplicas: 10<br>  metrics:<br>    - type: Resource<br>      resource:<br>        name: cpu<br>        target:<br>          type: Utilization<br>          averageUtilization: 70</pre><p>Interview answer:</p><blockquote><em>For payment workloads, I would use multiple replicas across nodes and configure HPA based on CPU, memory, or custom metrics such as request latency, queue depth, or Kafka consumer lag.</em></blockquote><h3>Q15. What is HPA?</h3><p><strong>Answer:</strong></p><p>HPA stands for Horizontal Pod Autoscaler. It automatically increases or decreases the number of Pod replicas based on metrics.</p><p>Senior-level answer:</p><blockquote><em>In a payment system, CPU alone may not be enough. Kafka consumer lag, API latency, pending transaction count, or queue depth can be better scaling indicators.</em></blockquote><h3>Q16. How do you make a Kubernetes deployment highly available?</h3><p><strong>Answer:</strong></p><p>I would use:</p><ol><li>Multiple replicas</li><li>Pod anti-affinity to avoid placing all Pods on the same node</li><li>Readiness and liveness probes</li><li>Resource requests and limits</li><li>Rolling updates</li><li>HPA</li><li>PodDisruptionBudget</li><li>Multi-zone node pools</li><li>Monitoring and alerting</li></ol><p>Example:</p><pre>apiVersion: policy/v1<br>kind: PodDisruptionBudget<br>metadata:<br>  name: payment-service-pdb<br>spec:<br>  minAvailable: 2<br>  selector:<br>    matchLabels:<br>      app: payment-service</pre><p>Interview version:</p><blockquote><em>For critical payment APIs, I would not run a single Pod. I would run at least three replicas across multiple nodes/zones, define readiness probes, use PodDisruptionBudget, and ensure rolling updates do not take all instances down at once.</em></blockquote><h3>8. Rolling deployment, rollback, blue-green, canary</h3><h3>Q17. How does rolling deployment work?</h3><p><strong>Answer:</strong></p><p>Rolling deployment gradually replaces old Pods with new Pods without downtime.</p><p>Example:</p><pre>strategy:<br>  type: RollingUpdate<br>  rollingUpdate:<br>    maxUnavailable: 1<br>    maxSurge: 1</pre><p>Interview answer:</p><blockquote><em>Kubernetes creates new Pods with the new version and slowly terminates old Pods. Readiness probes ensure that only healthy new Pods receive traffic.</em></blockquote><h3>Q18. How do you rollback a failed deployment?</h3><p>Commands:</p><pre>kubectl rollout history deployment payment-service<br>kubectl rollout undo deployment payment-service<br>kubectl rollout status deployment payment-service</pre><p>Interview answer:</p><blockquote><em>If a new version causes failures, I would first check logs, events, metrics, and rollout status. If customer impact is high, I would rollback immediately using </em><em>kubectl rollout undo or revert through the CI/CD pipeline.</em></blockquote><h3>Q19. What is canary deployment?</h3><p><strong>Answer:</strong></p><p>Canary deployment releases the new version to a small percentage of traffic first. If metrics are good, we gradually increase traffic.</p><p>Example:</p><blockquote><em>For a payment service, I may route 5% traffic to version 2 and 95% to version 1. I would monitor error rate, latency, failed transaction count, and rollback if issues increase.</em></blockquote><p><a href="https://dildeepak.medium.com/top-30-spring-boot-interview-questions-with-answers-for-experienced-java-developer-764e9172239d">Top 30 Spring Boot Interview Questions with Answers for Experienced Java Developer</a></p><h3>Q20. Blue-green vs canary deployment?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*cGKpj9y_xElSb3ocD1FUMw.jpeg" /></figure><p>Interview answer:</p><blockquote><em>Blue-green is faster for full cutover and rollback, but requires more infrastructure. Canary is safer for gradual rollout, especially for high-risk services like payments.</em></blockquote><h3>9. Resource requests and limits</h3><h3>Q21. What are resource requests and limits?</h3><p><strong>Answer:</strong></p><p>Requests define the minimum CPU/memory needed for scheduling. Limits define the maximum CPU/memory a container can use.</p><p>Example:</p><pre>resources:<br>  requests:<br>    cpu: &quot;500m&quot;<br>    memory: &quot;512Mi&quot;<br>  limits:<br>    cpu: &quot;1&quot;<br>    memory: &quot;1Gi&quot;</pre><p>Interview answer:</p><blockquote><em>Requests help Kubernetes schedule the Pod on a node with enough capacity. Limits prevent one container from consuming too many resources and affecting other services.</em></blockquote><h3>Q22. What happens if memory limit is exceeded?</h3><p><strong>Answer:</strong></p><p>The container may be killed with an OOMKilled error.</p><p>Troubleshooting command:</p><pre>kubectl describe pod payment-service-pod</pre><p>Look for:</p><pre>Reason: OOMKilled</pre><h3>Q23. What happens if CPU limit is exceeded?</h3><p><strong>Answer:</strong></p><p>The container is throttled, not killed. This can increase latency.</p><p>Senior-level answer:</p><blockquote><em>For latency-sensitive payment APIs, CPU throttling can cause timeout issues. I would monitor CPU throttling metrics and tune requests/limits properly.</em></blockquote><h3>10. Troubleshooting questions</h3><h3>Q24. A Pod is stuck in Pending state. What do you check?</h3><p><strong>Answer:</strong></p><p>I would check:</p><pre>kubectl describe pod &lt;pod-name&gt;<br>kubectl get nodes<br>kubectl describe node &lt;node-name&gt;</pre><p>Possible reasons:</p><p>ReasonExplanationInsufficient CPU/memoryNode does not have enough resourcesNode taintsPod does not tolerate node taintPVC issueStorage not boundImage pull secret issuePrivate image cannot be pulledAffinity rulesScheduling constraints too strict</p><p>Interview answer:</p><blockquote><em>Pending usually means Kubernetes cannot schedule the Pod. I would start with </em><em>kubectl describe pod because events clearly show the scheduling failure reason.</em></blockquote><h3>Q25. A Pod is in CrashLoopBackOff. How do you debug?</h3><p>Commands:</p><pre>kubectl logs &lt;pod-name&gt;<br>kubectl logs &lt;pod-name&gt; --previous<br>kubectl describe pod &lt;pod-name&gt;<br>kubectl get events</pre><p>Possible reasons:</p><ol><li>Application startup failure</li><li>Missing environment variable</li><li>Wrong secret/config</li><li>Database connection failure</li><li>Bad image version</li><li>Failing liveness probe</li><li>Port mismatch</li><li>Out of memory</li></ol><p>Strong interview answer:</p><blockquote><em>I would check the previous container logs first because CrashLoopBackOff means the container started and then crashed. Then I would check events, environment variables, probes, recent deployment changes, and dependent services.</em></blockquote><h3>Q26. Service is not reachable. What do you check?</h3><p>Commands:</p><pre>kubectl get svc<br>kubectl get endpoints payment-service<br>kubectl get pods --show-labels<br>kubectl describe svc payment-service</pre><p>Things to verify:</p><p>CheckWhyService selectorShould match Pod labelsTarget portShould match container portReadiness probeFailed Pods are removed from endpointsNetworkPolicyMay block trafficDNSService name resolution issueIngress configWrong path/host routing</p><p>Interview answer:</p><blockquote><em>One common issue is selector mismatch. The Service may exist, but if labels do not match the Pods, the Service will have no endpoints.</em></blockquote><h3>Q27. Application is running but receiving no traffic. Why?</h3><p>Possible causes:</p><ol><li>Readiness probe failing</li><li>Service selector mismatch</li><li>Ingress route misconfigured</li><li>NetworkPolicy blocking traffic</li><li>Wrong container port or targetPort</li><li>Pod is not in Running state</li><li>External load balancer health check failing</li></ol><p>Command:</p><pre>kubectl get endpoints payment-service</pre><p>If no endpoints exist, traffic will not reach Pods.</p><h3>11. Security questions</h3><h3>Q28. How do you secure Kubernetes workloads?</h3><p><strong>Answer:</strong></p><p>I would secure Kubernetes at multiple levels:</p><ol><li>Use RBAC with least privilege</li><li>Use namespaces for isolation</li><li>Store secrets securely</li><li>Enable encryption at rest</li><li>Use NetworkPolicy</li><li>Use non-root containers</li><li>Scan container images</li><li>Use trusted base images</li><li>Use admission policies</li><li>Restrict service account permissions</li></ol><p>Example:</p><pre>securityContext:<br>  runAsNonRoot: true<br>  runAsUser: 1000<br>  allowPrivilegeEscalation: false</pre><p>Senior-level answer:</p><blockquote><em>For financial/payment systems, security is not only application-level. Kubernetes cluster access, image security, secret management, network isolation, and audit logging are equally important.</em></blockquote><h3>Q29. What is RBAC?</h3><p><strong>Answer:</strong></p><p>RBAC stands for Role-Based Access Control. It controls who can perform what action on Kubernetes resources.</p><p>Example:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  namespace: payments<br>  name: pod-reader<br>rules:<br>  - apiGroups: [&quot;&quot;]<br>    resources: [&quot;pods&quot;]<br>    verbs: [&quot;get&quot;, &quot;watch&quot;, &quot;list&quot;]</pre><p>Interview answer:</p><blockquote><em>I would avoid giving developers cluster-admin access. Instead, I would assign namespace-level roles based on job responsibility.</em></blockquote><h3>Q30. What is NetworkPolicy?</h3><p><strong>Answer:</strong></p><p>NetworkPolicy controls traffic between Pods.</p><p>Example:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: allow-payment-to-ledger<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: ledger-service<br>  ingress:<br>    - from:<br>        - podSelector:<br>            matchLabels:<br>              app: payment-service<br>      ports:<br>        - protocol: TCP<br>          port: 8080</pre><p>Interview answer:</p><blockquote><em>In a payment system, not every service should communicate with every other service. NetworkPolicy helps enforce service-to-service boundaries.</em></blockquote><h3>12. Kubernetes with Spring Boot</h3><h3>Q31. How do you deploy a Spring Boot application to Kubernetes?</h3><p>Steps:</p><ol><li>Build Spring Boot JAR</li><li>Create Docker image</li><li>Push image to registry</li><li>Create Kubernetes Deployment</li><li>Create Kubernetes Service</li><li>Configure ConfigMap/Secret</li><li>Add health probes using Spring Boot Actuator</li><li>Deploy using CI/CD</li></ol><p>Dockerfile:</p><pre>FROM eclipse-temurin:17-jre<br>WORKDIR /app<br>COPY target/payment-service.jar app.jar<br>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>Deployment:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: payment-service<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: payment-service<br>  template:<br>    metadata:<br>      labels:<br>        app: payment-service<br>    spec:<br>      containers:<br>        - name: payment-service<br>          image: registry.example.com/payment-service:1.0<br>          ports:<br>            - containerPort: 8080<br>          envFrom:<br>            - configMapRef:<br>                name: payment-config<br>            - secretRef:<br>                name: payment-secret<br>          readinessProbe:<br>            httpGet:<br>              path: /actuator/health/readiness<br>              port: 8080<br>          livenessProbe:<br>            httpGet:<br>              path: /actuator/health/liveness<br>              port: 8080</pre><h3>Q32. Which Spring Boot Actuator endpoints are useful in Kubernetes?</h3><p>Useful endpoints:</p><pre>/actuator/health<br>/actuator/health/liveness<br>/actuator/health/readiness<br>/actuator/metrics<br>/actuator/prometheus</pre><p>In application.yml:</p><pre>management:<br>  endpoint:<br>    health:<br>      probes:<br>        enabled: true<br>  endpoints:<br>    web:<br>      exposure:<br>        include: health,metrics,prometheus</pre><p>Interview answer:</p><blockquote><em>Spring Boot Actuator integrates well with Kubernetes probes. I would expose readiness and liveness endpoints and use Prometheus metrics for observability.</em></blockquote><h3>13. Payments-focused scenario questions</h3><h3>Q33. Your payment service has 3 Pods. One Pod is failing intermittently. What happens?</h3><p><strong>Answer:</strong></p><p>If readiness probe fails, Kubernetes removes that Pod from the Service endpoints, so traffic goes only to healthy Pods. If liveness probe fails, Kubernetes restarts the unhealthy container. Meanwhile, the Deployment keeps the desired replica count.</p><p>Senior answer:</p><blockquote><em>For payment services, I would also check if the failure is due to DB connection pool exhaustion, downstream timeout, Kafka lag, memory pressure, or bad configuration on only one Pod.</em></blockquote><h3>Q34. During deployment, payment failures increased. What do you do?</h3><p><strong>Answer:</strong></p><p>I would follow this process:</p><ol><li>Check rollout status:</li></ol><pre>kubectl rollout status deployment payment-service</pre><ol><li>Check new Pod logs:</li></ol><pre>kubectl logs -l app=payment-service</pre><ol><li>Check events:</li></ol><pre>kubectl get events --sort-by=.metadata.creationTimestamp</pre><ol><li>Compare metrics between old and new version.</li><li>If customer impact is high, rollback:</li></ol><pre>kubectl rollout undo deployment payment-service</pre><p>Strong interview answer:</p><blockquote><em>In payments, rollback decision should be quick if failed transaction rate increases. Debugging can continue after stabilizing the platform.</em></blockquote><h3>Q35. Kafka consumer service running on Kubernetes is processing duplicate messages. Is Kubernetes responsible?</h3><p><strong>Answer:</strong></p><p>Not directly. Kubernetes manages container lifecycle, but duplicate processing is usually caused by Kafka offset handling, consumer restart, retry logic, or lack of idempotency.</p><p>Good answer:</p><blockquote><em>Since Pods can restart anytime in Kubernetes, Kafka consumers must be designed with idempotency. I would use transaction ID, message ID, or idempotency key to ensure duplicate messages do not create duplicate payment records.</em></blockquote><h3>Q36. How do you scale Kafka consumers in Kubernetes?</h3><p><strong>Answer:</strong></p><p>We can increase the number of replicas of the consumer Deployment, but the number of active consumers in a Kafka consumer group cannot exceed the number of partitions.</p><p>Example:</p><pre>kubectl scale deployment payment-consumer --replicas=6</pre><p>Interview answer:</p><blockquote><em>If the topic has 3 partitions and I run 6 consumer Pods in the same group, only 3 will actively consume. So scaling consumer Pods should be aligned with Kafka partition count and consumer lag.</em></blockquote><h3>Q37. How do you avoid downtime during deployment?</h3><p><strong>Answer:</strong></p><p>Use:</p><ol><li>Rolling updates</li><li>Readiness probe</li><li>Graceful shutdown</li><li>preStop hook</li><li>Proper termination grace period</li><li>Multiple replicas</li><li>PodDisruptionBudget</li></ol><p>Example:</p><pre>terminationGracePeriodSeconds: 60<br>lifecycle:<br>  preStop:<br>    exec:<br>      command: [&quot;sh&quot;, &quot;-c&quot;, &quot;sleep 10&quot;]</pre><p>Spring Boot config:</p><pre>server:<br>  shutdown: graceful</pre><pre>spring:<br>  lifecycle:<br>    timeout-per-shutdown-phase: 30s</pre><p>Interview answer:</p><blockquote><em>For payment APIs, graceful shutdown is important because we should not kill a Pod while it is processing an active transaction.</em></blockquote><h3>14. Common kubectl commands you should know</h3><h3>Cluster and nodes</h3><pre>kubectl get nodes<br>kubectl describe node &lt;node-name&gt;</pre><h3>Pods</h3><pre>kubectl get pods<br>kubectl get pods -o wide<br>kubectl describe pod &lt;pod-name&gt;<br>kubectl logs &lt;pod-name&gt;<br>kubectl logs &lt;pod-name&gt; --previous<br>kubectl exec -it &lt;pod-name&gt; -- sh</pre><h3>Deployments</h3><pre>kubectl get deployments<br>kubectl describe deployment payment-service<br>kubectl rollout status deployment payment-service<br>kubectl rollout history deployment payment-service<br>kubectl rollout undo deployment payment-service</pre><h3>Services</h3><pre>kubectl get svc<br>kubectl describe svc payment-service<br>kubectl get endpoints payment-service</pre><h3>Config and secrets</h3><pre>kubectl get configmap<br>kubectl get secret</pre><h3>Events</h3><pre>kubectl get events --sort-by=.metadata.creationTimestamp</pre><h3>Namespace</h3><pre>kubectl get ns<br>kubectl get pods -n payments</pre><h3>15. Scenario-based answers for senior interviews</h3><h3>Scenario 1: Pod keeps restarting</h3><p>Good answer:</p><blockquote><em>I would first check </em><em>kubectl logs --previous because the current container may not show the crash reason. Then I would check </em><em>kubectl describe pod for events such as OOMKilled, failed probe, image pull issue, or config problem. I would also verify recent deployment changes, environment variables, secrets, and downstream dependencies like DB or Kafka.</em></blockquote><h3>Scenario 2: New deployment is successful but API gives 503</h3><p>Good answer:</p><blockquote><em>I would check whether the Service has healthy endpoints using </em><em>kubectl get endpoints. If endpoints are missing, the issue may be readiness probe failure or label mismatch between Service selector and Pod labels. I would also check Ingress rules, targetPort, containerPort, and application logs.</em></blockquote><h3>Scenario 3: Payment API latency increased after scaling</h3><p>Good answer:</p><blockquote><em>Scaling Pods does not automatically solve all latency issues. I would check CPU throttling, memory pressure, DB connection pool limits, downstream service limits, Kafka lag, and network latency. Sometimes adding more Pods increases pressure on shared dependencies like database or external APIs.</em></blockquote><h3>Scenario 4: How would you deploy 10 microservices?</h3><p>Good answer:</p><blockquote><em>I would containerize each service separately and create independent Kubernetes Deployments and Services. Configuration would be externalized using ConfigMaps and Secrets. Internal services would use ClusterIP, external APIs would be exposed through Ingress/API Gateway. Each service would have probes, resource limits, HPA, logging, metrics, and CI/CD-based deployment. For payments, I would also enforce network policies, audit logging, and idempotent processing.</em></blockquote><h3>Scenario 5: How do you handle secrets in Kubernetes?</h3><p>Good answer:</p><blockquote><em>I would avoid hardcoding secrets in Docker images or YAML files. Kubernetes Secrets can be used, but in production I prefer integration with cloud secret managers like AWS Secrets Manager, GCP Secret Manager, or Vault. I would also enable encryption at rest and restrict access using RBAC.</em></blockquote><h3>16. Questions you may be asked directly</h3><p>Prepare these especially:</p><ol><li>What is Kubernetes and why do we use it?</li><li>Difference between Docker and Kubernetes?</li><li>What is a Pod?</li><li>What is a Deployment?</li><li>What is a ReplicaSet?</li><li>What is a Service?</li><li>Difference between ClusterIP, NodePort, and LoadBalancer?</li><li>What is Ingress?</li><li>What are ConfigMap and Secret?</li><li>What is the difference between readiness and liveness probe?</li><li>How do you troubleshoot CrashLoopBackOff?</li><li>How do you troubleshoot ImagePullBackOff?</li><li>How do you rollback a deployment?</li><li>How do you scale Pods?</li><li>What is HPA?</li><li>How do you manage zero-downtime deployment?</li><li>How do you secure Kubernetes?</li><li>What is RBAC?</li><li>What is NetworkPolicy?</li><li>What is Namespace?</li><li>What are resource requests and limits?</li><li>What is OOMKilled?</li><li>How do microservices communicate inside Kubernetes?</li><li>How do you expose APIs outside the cluster?</li><li>How do you monitor Kubernetes applications?</li><li>How do you deploy Spring Boot app in Kubernetes?</li><li>What happens if a node fails?</li><li>What happens if a Pod fails?</li><li>How do you handle configuration across environments?</li><li>How do you handle Kafka consumers in Kubernetes?</li></ol><h3>17. Very strong answer: Docker vs Kubernetes</h3><blockquote><em>Docker is used to package and run applications as containers. Kubernetes is used to orchestrate those containers in production. Docker solves the packaging problem, while Kubernetes solves deployment, scaling, networking, self-healing, service discovery, rollout, rollback, and high availability.</em></blockquote><h3>18. Very strong answer: Kubernetes in your project</h3><p>You can say this in the interview:</p><blockquote><em>In my project, we had multiple Spring Boot microservices such as payment, account, transaction, notification, and reconciliation services. Each service was containerized using Docker and deployed to Kubernetes as a Deployment. We used Services for internal communication and Ingress/API Gateway for external routing. Configuration was managed using ConfigMaps and Secrets.</em></blockquote><blockquote><em>For reliability, we configured readiness and liveness probes using Spring Boot Actuator. We used rolling deployments to avoid downtime and rollback strategy in case of production issues. For scalability, we used multiple replicas and autoscaling. Logs and metrics were integrated with monitoring tools, and for critical flows like payments, we ensured idempotency because Kubernetes Pods can restart or scale at any time.</em></blockquote><h3>19. 5-day Kubernetes prep plan for interview</h3><h3>Day 1: Core concepts</h3><p>Focus on:</p><pre>Pod<br>Deployment<br>ReplicaSet<br>Service<br>Namespace<br>ConfigMap<br>Secret</pre><p>Practice explaining them in simple words.</p><h3>Day 2: Deployment and Spring Boot</h3><p>Practice:</p><pre>Dockerfile<br>Deployment YAML<br>Service YAML<br>Actuator health probes<br>ConfigMap/Secret injection</pre><h3>Day 3: Troubleshooting</h3><p>Practice commands:</p><pre>kubectl describe pod<br>kubectl logs<br>kubectl logs --previous<br>kubectl get events<br>kubectl get endpoints<br>kubectl rollout undo</pre><h3>Day 4: Scaling and reliability</h3><p>Focus on:</p><pre>HPA<br>resource requests/limits<br>rolling update<br>rollback<br>PDB<br>graceful shutdown</pre><h3>Day 5: Senior scenarios</h3><p>Practice:</p><pre>Payment service downtime<br>Kafka consumer scaling<br>Duplicate transaction prevention<br>High latency debugging<br>Secure deployment<br>Zero-downtime release</pre><h3>20. Final interview cheat sheet</h3><p>Remember these lines:</p><blockquote><em>Kubernetes does not make a bad application reliable automatically. The application still needs proper health checks, graceful shutdown, idempotency, retry handling, timeout handling, and observability.</em></blockquote><blockquote><em>In payment systems, Kubernetes helps with availability and scaling, but duplicate prevention must be handled at application and data level using idempotency keys and transaction status management.</em></blockquote><blockquote><em>For troubleshooting, I always start with </em><em>kubectl describe, </em><em>kubectl logs, </em><em>kubectl get events, and </em><em>kubectl get endpoints.</em></blockquote><blockquote><em>For production readiness, I focus on probes, resources, autoscaling, rollback, secrets, RBAC, network policy, logging, and monitoring.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=755696861b30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Interview Question — For Experienced Professional]]></title>
            <link>https://dildeepak.medium.com/kafka-interview-question-for-experienced-professional-15202727bee0?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/15202727bee0</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 03:19:24 GMT</pubDate>
            <atom:updated>2026-07-09T10:40:53.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*uTq-2-VYZlHzdvcCoOn9BA.jpeg" /></figure><p>Think of Kafka in your interview like this:</p><blockquote><em>Kafka is not just a messaging tool. In payment systems, Kafka is used as the event backbone for transaction processing, fraud checks, ledger posting, notifications, reconciliation, retries, and audit trails.</em></blockquote><h3><strong><em>~~~~~ Important Points from the Read ~~~~~</em></strong></h3><p># Kafka provides ordering within a partition, not across the entire topic.</p><p># Consumer group parallelism is limited by the number of partitions.</p><p># Kafka can redeliver messages, so consumers must be idempotent.</p><p># For payment systems, exactly-once should be treated carefully. Kafka exactly-once does not automatically cover database updates or external APIs.</p><p># DLQ should include failure reason, original topic, partition, offset, event ID, and correlation ID.</p><p># Consumer lag tells us whether downstream processing is keeping up.</p><p># For financial systems, auditability and reconciliation are just as important as message delivery.</p><p>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</p><h3>1. Kafka mental model</h3><p>Imagine a payment system:</p><pre>Payment API<br>   |<br>   | publishes event<br>   v<br>Kafka Topic: payment-events<br>   |<br>   | consumed by<br>   v<br>Fraud Service<br>Ledger Service<br>Notification Service<br>Reconciliation Service</pre><p>Kafka allows services to communicate asynchronously.</p><p>Instead of Payment API directly calling Ledger, Fraud, Notification, and Reconciliation one by one, it publishes an event:</p><pre>{<br>  &quot;paymentId&quot;: &quot;PAY123&quot;,<br>  &quot;amount&quot;: 250.00,<br>  &quot;currency&quot;: &quot;USD&quot;,<br>  &quot;status&quot;: &quot;INITIATED&quot;,<br>  &quot;merchantId&quot;: &quot;M123&quot;<br>}</pre><p>Then different services consume the event independently.</p><h3>2. How to explain Kafka in interview</h3><p>Use this answer:</p><blockquote><em>Kafka is a distributed event streaming platform used for asynchronous communication between microservices. It stores messages in topics, divides topics into partitions for scalability, and allows consumers to read messages using offsets.</em></blockquote><blockquote><em>In a payment platform, Kafka helps decouple services. For example, once a payment is initiated, the payment service can publish an event to Kafka. Fraud, ledger, notification, and reconciliation services can consume that event independently without blocking the payment API response.</em></blockquote><blockquote><em>Kafka also gives durability, replay capability, ordering within partitions, scalability through consumer groups, and fault tolerance through replication.</em></blockquote><h3>3. Core Kafka concepts</h3><h3>Q1. What is a Kafka topic?</h3><p>A topic is a logical stream of messages.</p><p>Example:</p><pre>payment-events<br>ledger-events<br>fraud-events<br>notification-events<br>reconciliation-events</pre><p>Interview answer:</p><blockquote><em>A topic is like a category or channel where producers publish messages and consumers read messages. For example, all payment-related events can go to a </em><em>payment-events topic.</em></blockquote><h3>Q2. What is a Kafka partition?</h3><p>A topic is split into partitions.</p><pre>payment-events<br>  Partition 0<br>  Partition 1<br>  Partition 2</pre><p>Partitions help Kafka scale.</p><p>Important point:</p><blockquote><em>Ordering is guaranteed only within a partition, not across the whole topic.</em></blockquote><p>Example:</p><p>If all events for the same paymentId go to the same partition, their order is preserved.</p><pre>paymentId = PAY123<br>INITIATED -&gt; FRAUD_CHECKED -&gt; COMPLETED</pre><p>Senior answer:</p><blockquote><em>For payments, I would usually use </em><em>paymentId, </em><em>accountId, or </em><em>merchantId as the Kafka message key depending on what ordering guarantee I need.</em></blockquote><h3>Q3. What is a Kafka producer?</h3><p>A producer publishes messages to Kafka.</p><p>Example:</p><pre>Payment Service -&gt; Kafka topic</pre><p>Spring Boot example:</p><pre>@Service<br>public class PaymentEventProducer {</pre><pre>    private final KafkaTemplate&lt;String, PaymentEvent&gt; kafkaTemplate;</pre><pre>    public PaymentEventProducer(KafkaTemplate&lt;String, PaymentEvent&gt; kafkaTemplate) {<br>        this.kafkaTemplate = kafkaTemplate;<br>    }</pre><pre>    public void publishPaymentEvent(PaymentEvent event) {<br>        kafkaTemplate.send(&quot;payment-events&quot;, event.getPaymentId(), event);<br>    }<br>}</pre><p>Important:</p><pre>kafkaTemplate.send(&quot;payment-events&quot;, event.getPaymentId(), event);</pre><p>Here, paymentId is the key. This helps send all events for the same payment to the same partition.</p><h3>Q4. What is a Kafka consumer?</h3><p>A consumer reads messages from Kafka.</p><p>Example:</p><pre>@Component<br>public class PaymentEventConsumer {</pre><pre>    @KafkaListener(<br>        topics = &quot;payment-events&quot;,<br>        groupId = &quot;ledger-service-group&quot;<br>    )<br>    public void consume(PaymentEvent event) {<br>        System.out.println(&quot;Processing payment: &quot; + event.getPaymentId());<br>    }<br>}</pre><p>Interview answer:</p><blockquote><em>A consumer subscribes to a topic and processes messages. In a payment system, the ledger service may consume payment events and create ledger entries.</em></blockquote><p><a href="https://dildeepak.medium.com/kubernetes-interview-questions-for-experienced-you-shouldnt-attend-any-exam-without-them-755696861b30">Kubernetes Interview Questions for Experienced — You shouldn’t attend any exam without them</a></p><h3>Q5. What is a consumer group?</h3><p>A consumer group is a group of consumers sharing the workload of a topic.</p><p>Example:</p><pre>Topic: payment-events<br>Partitions: 3</pre><pre>Consumer Group: ledger-service-group<br>  Consumer 1 -&gt; Partition 0<br>  Consumer 2 -&gt; Partition 1<br>  Consumer 3 -&gt; Partition 2</pre><p>If you add a fourth consumer but only have three partitions:</p><pre>Consumer 4 -&gt; idle</pre><p>Interview answer:</p><blockquote><em>In Kafka, only one consumer from the same consumer group can read from a partition at a time. So the maximum parallelism of a consumer group is limited by the number of partitions.</em></blockquote><h3>4. Most important Kafka interview questions</h3><h3>Q6. Difference between Kafka and traditional messaging queues?</h3><p>KafkaTraditional QueueMessages are retained for configured timeMessages are usually removed after consumptionMultiple consumer groups can read same messageUsually one consumer consumes one messageSupports replayReplay is harderHigh throughputLower throughput in many casesDistributed log modelQueue model</p><p>Strong answer:</p><blockquote><em>Kafka is more like a distributed commit log than a simple queue. Messages are stored for a retention period and consumers track their own offsets. This allows replay, multiple independent consumers, and event-driven architecture.</em></blockquote><h3>Q7. What is offset?</h3><p>Offset is the position of a message inside a partition.</p><p>Example:</p><pre>Partition 0:<br>offset 0 -&gt; payment initiated<br>offset 1 -&gt; payment validated<br>offset 2 -&gt; payment completed</pre><p>Interview answer:</p><blockquote><em>Offset tells Kafka which message a consumer has already processed. Consumers commit offsets so they can resume from the right position after restart.</em></blockquote><h3>Q8. What happens if a Kafka consumer crashes?</h3><p>Answer:</p><blockquote><em>If a consumer crashes, Kafka triggers a rebalance. The partitions assigned to that consumer are reassigned to other consumers in the same group. The new consumer starts reading from the last committed offset.</em></blockquote><p>Important senior point:</p><blockquote><em>If the offset was committed before processing completed, we may lose the message. If the offset was committed after processing, we may process the same message again after crash. That is why idempotency is critical.</em></blockquote><p><a href="https://dildeepak.medium.com/spring-core-and-spring-boot-interview-questions-for-experienced-professional-75b18da2a176">Spring Core and Spring Boot Interview Questions for Experienced Professional</a></p><h3>5. Real-time situation-based Kafka questions</h3><h3>Scenario 1: Duplicate payment events are being processed</h3><h3>Interviewer asks:</h3><p>Your Kafka consumer processed the same payment event twice and created duplicate ledger entries. How would you fix it?</p><h3>Strong answer:</h3><blockquote><em>Kafka usually provides at-least-once delivery, which means duplicate consumption can happen, especially when a consumer crashes after processing but before committing the offset.</em></blockquote><blockquote><em>I would not rely only on Kafka to prevent duplicates. I would make the consumer idempotent. For payment systems, each event should have a unique </em><em>eventId, </em><em>paymentId, or </em><em>idempotencyKey. Before creating a ledger entry, the consumer should check whether that event has already been processed.</em></blockquote><blockquote><em>At the database level, I would add a unique constraint on </em><em>event_id or </em><em>payment_id + event_type. This guarantees duplicate messages do not create duplicate financial records.</em></blockquote><p>Example table:</p><pre>CREATE TABLE processed_events (<br>    event_id VARCHAR(100) PRIMARY KEY,<br>    payment_id VARCHAR(100),<br>    event_type VARCHAR(50),<br>    processed_at TIMESTAMP<br>);</pre><p>Consumer logic:</p><pre>@Transactional<br>public void processPaymentEvent(PaymentEvent event) {</pre><pre>    if (processedEventRepository.existsById(event.getEventId())) {<br>        return;<br>    }</pre><pre>    ledgerRepository.save(new LedgerEntry(<br>        event.getPaymentId(),<br>        event.getAmount(),<br>        event.getCurrency()<br>    ));</pre><pre>    processedEventRepository.save(new ProcessedEvent(event.getEventId()));<br>}</pre><p>Best interview line:</p><blockquote><em>In payment systems, duplicate prevention must be handled at the application and database level, not only at Kafka level.</em></blockquote><h3>Scenario 2: Kafka consumer is slow and lag is increasing</h3><h3>Interviewer asks:</h3><p>Your payment consumer is falling behind. Kafka lag is increasing. What do you check?</p><h3>Strong answer:</h3><blockquote><em>I would first identify whether the bottleneck is Kafka, the consumer application, or a downstream dependency. Kafka lag means messages are arriving faster than consumers are processing them.</em></blockquote><blockquote><em>I would check consumer processing time, database latency, downstream API latency, CPU/memory usage, thread pool saturation, Kafka partition count, and number of consumer instances.</em></blockquote><blockquote><em>If partitions are enough, I can scale consumer replicas. If partitions are fewer, adding more consumers will not help beyond the partition count. I may also optimize batch processing, database writes, and retry logic.</em></blockquote><p>Checklist:</p><pre>1. Check consumer lag<br>2. Check number of partitions<br>3. Check number of consumer pods<br>4. Check DB latency<br>5. Check downstream service latency<br>6. Check retry storm<br>7. Check CPU/memory<br>8. Check message size<br>9. Check error logs<br>10. Scale consumers if partition count allows</pre><p>Best answer:</p><blockquote><em>Scaling consumers only helps if the topic has enough partitions.</em></blockquote><h3>Scenario 3: You have 3 partitions and 6 consumers. What happens?</h3><h3>Answer:</h3><blockquote><em>Only 3 consumers will actively consume. The remaining 3 consumers will stay idle because a partition can be assigned to only one consumer within the same consumer group.</em></blockquote><p>Example:</p><pre>Partition 0 -&gt; Consumer 1<br>Partition 1 -&gt; Consumer 2<br>Partition 2 -&gt; Consumer 3<br>Consumer 4 -&gt; idle<br>Consumer 5 -&gt; idle<br>Consumer 6 -&gt; idle</pre><p>Senior explanation:</p><blockquote><em>Kafka parallelism is controlled by partition count. If I need higher parallel processing, I need to plan partition count properly.</em></blockquote><h3>Scenario 4: Same message should be consumed by multiple services</h3><h3>Interviewer asks:</h3><p>Payment event should be consumed by Ledger Service, Fraud Service, and Notification Service. How do you design it?</p><h3>Answer:</h3><p>Use different consumer groups.</p><pre>Topic: payment-events</pre><pre>Consumer Group 1: ledger-service-group<br>Consumer Group 2: fraud-service-group<br>Consumer Group 3: notification-service-group</pre><p>Each group receives its own copy of the message.</p><p>Strong answer:</p><blockquote><em>If multiple services need to independently process the same event, each service should have its own consumer group. Kafka stores the event once, but each consumer group maintains its own offset.</em></blockquote><h3>Scenario 5: You need ordering for payment events</h3><h3>Interviewer asks:</h3><p>How do you guarantee that payment events are processed in order?</p><h3>Answer:</h3><blockquote><em>Kafka guarantees ordering only within a partition. So I would use a proper message key, such as </em><em>paymentId, so all events for the same payment go to the same partition.</em></blockquote><p>Example:</p><pre>kafkaTemplate.send(&quot;payment-events&quot;, paymentEvent.getPaymentId(), paymentEvent);</pre><p>This ensures:</p><pre>PAY123 INITIATED<br>PAY123 VALIDATED<br>PAY123 COMPLETED</pre><p>go to the same partition.</p><p>Important:</p><blockquote><em>Kafka does not guarantee global ordering across all partitions. It guarantees ordering per partition.</em></blockquote><h3>Scenario 6: Consumer failed while processing a payment</h3><h3>Interviewer asks:</h3><p>Consumer reads payment event, updates DB, but crashes before committing offset. What happens?</p><h3>Answer:</h3><blockquote><em>Since the offset was not committed, Kafka will redeliver the same message after the consumer restarts or after rebalance. This can cause duplicate processing.</em></blockquote><blockquote><em>To handle this safely, I would make processing idempotent using </em><em>eventId or </em><em>paymentId, and commit offset only after successful processing.</em></blockquote><p>Senior answer:</p><blockquote><em>This is why at-least-once delivery requires idempotent consumers.</em></blockquote><h3>Scenario 7: Consumer commits offset before DB update and then crashes</h3><h3>What happens?</h3><blockquote><em>This is dangerous. Kafka thinks the message is already processed, but the database update never happened. This can cause message loss from the business perspective.</em></blockquote><p>Better approach:</p><pre>1. Read message<br>2. Validate message<br>3. Process DB transaction<br>4. Save processed event<br>5. Commit offset</pre><p>Best answer:</p><blockquote><em>For critical financial events, I would avoid committing offsets before the business transaction completes.</em></blockquote><h3>Scenario 8: Downstream ledger service is down</h3><h3>Interviewer asks:</h3><p>Kafka consumer cannot call ledger service. What should happen?</p><h3>Strong answer:</h3><blockquote><em>I would avoid infinite immediate retries because that can create retry storms. I would use controlled retry with backoff. If the message still fails after configured retries, I would send it to a dead-letter topic for later investigation or replay.</em></blockquote><p>Flow:</p><pre>payment-events<br>   |<br>consumer<br>   |<br>failure<br>   |<br>retry with backoff<br>   |<br>still fails<br>   |<br>payment-events-dlt</pre><p>Spring Kafka example:</p><pre>@KafkaListener(topics = &quot;payment-events&quot;, groupId = &quot;ledger-service-group&quot;)<br>public void consume(PaymentEvent event) {<br>    ledgerService.process(event);<br>}</pre><p>Retry/DLT can be configured using Spring Kafka error handlers.</p><p>Interview answer:</p><blockquote><em>For payments, I would also alert on dead-letter topic count because failed payment events may require operational action or reconciliation.</em></blockquote><h3>Scenario 9: Message goes to DLQ. What next?</h3><h3>Answer:</h3><blockquote><em>A DLQ is not the end of the flow. We need monitoring, alerting, root-cause analysis, and replay strategy.</em></blockquote><blockquote><em>I would store failure reason, exception type, timestamp, original topic, original partition, original offset, and correlation ID. After fixing the issue, we can replay messages from DLQ safely using idempotent processing.</em></blockquote><p>DLQ message metadata:</p><pre>{<br>  &quot;eventId&quot;: &quot;EVT123&quot;,<br>  &quot;paymentId&quot;: &quot;PAY123&quot;,<br>  &quot;error&quot;: &quot;Database timeout&quot;,<br>  &quot;originalTopic&quot;: &quot;payment-events&quot;,<br>  &quot;originalPartition&quot;: 2,<br>  &quot;originalOffset&quot;: 1456,<br>  &quot;failedAt&quot;: &quot;2026-07-05T10:15:00Z&quot;<br>}</pre><p>Best senior line:</p><blockquote><em>DLQ should be observable and replayable, not just a dumping ground.</em></blockquote><p><a href="https://dildeepak.medium.com/top-30-spring-boot-interview-questions-with-answers-for-experienced-java-developer-764e9172239d">Top 30 Spring Boot Interview Questions with Answers for Experienced Java Developer</a></p><h3>6. Kafka delivery semantics</h3><h3>Q1. What is at-most-once delivery?</h3><pre>Commit offset first, process later</pre><p>Risk:</p><pre>Message may be lost</pre><p>Not ideal for payments.</p><h3>Q2. What is at-least-once delivery?</h3><pre>Process first, commit offset later</pre><p>Risk:</p><pre>Message may be processed more than once</pre><p>Commonly used with idempotency.</p><p>Best for payments if designed properly.</p><h3>Q3. What is exactly-once delivery?</h3><p>Kafka supports exactly-once semantics for Kafka-to-Kafka workflows using idempotent producers and transactions.</p><p>But senior-level answer:</p><blockquote><em>Exactly-once in Kafka does not automatically mean exactly-once in the database or external payment gateway. Once the consumer interacts with an external system, we still need idempotency and transactional design.</em></blockquote><p>Best answer:</p><blockquote><em>In real payment systems, I design for effectively-once processing using at-least-once delivery plus idempotent consumers, unique keys, and transactional database writes.</em></blockquote><h3>7. Producer reliability questions</h3><h3>Q1. How do you make Kafka producer reliable?</h3><p>Use:</p><pre>acks=all<br>enable.idempotence=true<br>retries=3<br>delivery.timeout.ms=120000<br>request.timeout.ms=30000<br>max.in.flight.requests.per.connection=5</pre><p>Interview answer:</p><blockquote><em>I would use </em><em>acks=all so the producer waits for acknowledgement from all in-sync replicas. I would enable idempotent producer to avoid duplicate records during retries. For critical payment events, I would not use fire-and-forget publishing.</em></blockquote><h3>Q2. What is acks=0, acks=1, and acks=all?</h3><p>SettingMeaningRiskacks=0Producer does not waitFast but unsafeacks=1Leader acknowledgesMessage can be lost if leader fails before replicationacks=allAll in-sync replicas acknowledgeSafest</p><p>For payment systems:</p><blockquote><em>I would prefer </em><em>acks=all with proper replication and idempotence.</em></blockquote><h3>Q3. What is idempotent producer?</h3><p>Answer:</p><blockquote><em>An idempotent producer prevents duplicate messages caused by producer retries. If the producer sends the same message again due to retry, Kafka can detect and avoid duplicate writes to the partition.</em></blockquote><p>Important:</p><blockquote><em>Idempotent producer helps with producer-side duplicates, but consumers should still be idempotent.</em></blockquote><h3>8. Consumer reliability questions</h3><h3>Q1. Auto commit vs manual commit?</h3><h3>Auto commit</h3><p>Kafka commits offset automatically.</p><p>Risk:</p><blockquote><em>Offset may be committed before processing is complete.</em></blockquote><h3>Manual commit</h3><p>Application commits after successful processing.</p><p>Better for critical systems.</p><p>Spring Kafka example:</p><pre>@KafkaListener(topics = &quot;payment-events&quot;, groupId = &quot;ledger-service-group&quot;)<br>public void consume(PaymentEvent event, Acknowledgment ack) {<br>    try {<br>        ledgerService.process(event);<br>        ack.acknowledge();<br>    } catch (Exception ex) {<br>        throw ex;<br>    }<br>}</pre><p>Interview answer:</p><blockquote><em>For payment processing, I prefer manual commit because I want to commit the offset only after the business operation succeeds.</em></blockquote><h3>Q2. What happens during consumer rebalance?</h3><p>Answer:</p><blockquote><em>Rebalance happens when consumers join or leave a consumer group, or partitions are added. Kafka redistributes partitions among consumers. During rebalance, consumption can pause briefly.</em></blockquote><p>Senior answer:</p><blockquote><em>In production, frequent rebalances can hurt throughput and increase latency. I would check consumer crashes, long processing time, heartbeat settings, and deployment patterns.</em></blockquote><h3>Q3. What causes frequent rebalancing?</h3><p>Common reasons:</p><pre>1. Consumer crash<br>2. Long processing time<br>3. Heartbeat timeout<br>4. Kubernetes pod restart<br>5. Scaling up/down<br>6. Network issues<br>7. max.poll.interval.ms exceeded</pre><p>Strong answer:</p><blockquote><em>If message processing takes longer than </em><em>max.poll.interval.ms, Kafka may think the consumer is dead and trigger rebalance.</em></blockquote><h3>9. Kafka and Kubernetes together</h3><h3>Q1. Kafka consumer running in Kubernetes keeps restarting. What can happen?</h3><p>Answer:</p><blockquote><em>If a Kafka consumer Pod restarts before committing offset, messages may be reprocessed. This is expected in at-least-once delivery. Therefore, the consumer must be idempotent.</em></blockquote><p>Kubernetes + Kafka production concerns:</p><pre>Pod restart -&gt; duplicate consumption possible<br>Pod scaling -&gt; consumer rebalance<br>Pod crash -&gt; partition reassignment<br>Rolling deployment -&gt; temporary rebalance<br>Readiness failure -&gt; pod removed from service, but Kafka consumer may still need graceful shutdown</pre><h3>Q2. How do you safely deploy Kafka consumers on Kubernetes?</h3><p>Use:</p><pre>1. Graceful shutdown<br>2. Manual offset commit<br>3. Idempotent processing<br>4. Readiness/liveness probes<br>5. Controlled rolling deployment<br>6. Proper max.poll.interval.ms<br>7. Proper concurrency<br>8. DLQ and retry<br>9. Consumer lag monitoring</pre><p>Senior answer:</p><blockquote><em>During rolling deployment, I want each consumer Pod to stop cleanly, finish current processing, commit offset, and then shut down. Otherwise, the same event may be picked up again by another Pod.</em></blockquote><h3>10. Kafka topic design for payment system</h3><p>Example topics:</p><pre>payment-initiated<br>payment-validated<br>payment-authorized<br>payment-completed<br>payment-failed<br>ledger-posted<br>fraud-check-requested<br>fraud-check-completed<br>payment-retry<br>payment-dlt</pre><p>Alternative design:</p><pre>payment-events</pre><p>with event type:</p><pre>{<br>  &quot;eventType&quot;: &quot;PAYMENT_COMPLETED&quot;,<br>  &quot;paymentId&quot;: &quot;PAY123&quot;<br>}</pre><h3>Interview question: one topic or multiple topics?</h3><p>Strong answer:</p><blockquote><em>It depends on scale, ownership, retention, security, and consumer needs.</em></blockquote><blockquote><em>If all events belong to the same payment lifecycle and have similar retention/security needs, one </em><em>payment-events topic with event type can work.</em></blockquote><blockquote><em>If events have different consumers, retention policies, sensitivity, or throughput, separate topics may be better.</em></blockquote><p>Senior-level tradeoff:</p><p>DesignProsConsSingle topicSimpler, preserves payment lifecycle in one streamConsumers must filter eventsMultiple topicsClear separation, different retention/securityMore operational overhead</p><h3>11. Kafka schema evolution</h3><h3>Q1. What happens if producer changes message structure?</h3><p>Example:</p><p>Old event:</p><pre>{<br>  &quot;paymentId&quot;: &quot;PAY123&quot;,<br>  &quot;amount&quot;: 100<br>}</pre><p>New event:</p><pre>{<br>  &quot;paymentId&quot;: &quot;PAY123&quot;,<br>  &quot;amount&quot;: 100,<br>  &quot;currency&quot;: &quot;USD&quot;<br>}</pre><p>Answer:</p><blockquote><em>If consumers are not compatible with the new schema, they may fail. To avoid this, we use schema evolution rules and backward/forward compatibility.</em></blockquote><p>Good answer:</p><blockquote><em>I would avoid breaking changes like removing fields or changing data types directly. I would add optional fields, version the schema, and use Schema Registry if using Avro/Protobuf/JSON Schema.</em></blockquote><h3>Q2. How do you handle backward compatibility?</h3><p>Good practices:</p><pre>1. Add optional fields instead of removing fields<br>2. Do not change field type suddenly<br>3. Use default values<br>4. Version event schemas<br>5. Use Schema Registry<br>6. Test consumer compatibility in CI/CD</pre><p>Interview answer:</p><blockquote><em>In microservices, producer and consumer deployments may not happen at the same time. So events must be backward compatible.</em></blockquote><h3>12. Kafka monitoring and observability</h3><h3>Q1. What metrics do you monitor?</h3><p>For producer:</p><pre>record-send-rate<br>record-error-rate<br>request-latency<br>retry-rate</pre><p>For consumer:</p><pre>consumer lag<br>records consumed rate<br>processing latency<br>commit latency<br>rebalance count<br>DLQ count</pre><p>For broker:</p><pre>under-replicated partitions<br>offline partitions<br>disk usage<br>network I/O<br>ISR shrink/expand<br>controller changes</pre><p>Payment-specific:</p><pre>payment failure rate<br>duplicate event count<br>ledger posting delay<br>reconciliation mismatch count<br>DLQ payment events<br>fraud decision delay</pre><p>Strong answer:</p><blockquote><em>For payments, consumer lag is not just a technical metric. It may mean ledger updates, notifications, or reconciliation are delayed.</em></blockquote><h3>13. Real production troubleshooting questions</h3><h3>Scenario: Payment events are published but ledger service is not processing</h3><p>Check:</p><pre>1. Is producer publishing to correct topic?<br>2. Is ledger consumer using correct topic?<br>3. Is consumer group active?<br>4. Is consumer lag increasing?<br>5. Are partitions assigned?<br>6. Are messages failing deserialization?<br>7. Is the consumer stuck due to DB/downstream issue?<br>8. Are messages going to DLQ?<br>9. Was there a schema change?<br>10. Did Kubernetes restart the consumer pods?</pre><p>Useful commands:</p><pre>kafka-consumer-groups --bootstrap-server localhost:9092 \<br>  --describe --group ledger-service-group</pre><p>Kubernetes:</p><pre>kubectl logs -l app=ledger-service<br>kubectl describe pod &lt;ledger-pod&gt;<br>kubectl get events</pre><h3>Scenario: Consumer is reading old messages after restart</h3><p>Possible reasons:</p><pre>1. Offset was not committed<br>2. Consumer group changed<br>3. auto.offset.reset=earliest<br>4. Offset was reset manually<br>5. New consumer group started</pre><p>Answer:</p><blockquote><em>If the consumer group ID changes, Kafka treats it as a new consumer group and starts based on </em><em>auto.offset.reset.</em></blockquote><h3>Scenario: Kafka message ordering is broken</h3><p>Possible causes:</p><pre>1. No message key<br>2. Wrong key used<br>3. Same payment events going to different partitions<br>4. Multiple topics without sequencing<br>5. Retry/DLQ replay changed order<br>6. Parallel processing inside consumer</pre><p>Strong answer:</p><blockquote><em>To maintain order for a payment, I would ensure all events for the same </em><em>paymentId use the same key and are processed sequentially within that partition.</em></blockquote><h3>14. Senior-level Kafka design question</h3><h3>Design event-driven payment processing using Kafka</h3><h3>Requirements</h3><pre>1. Payment API receives request<br>2. Validate payment<br>3. Run fraud check<br>4. Authorize payment<br>5. Post ledger entry<br>6. Notify customer<br>7. Support retry and DLQ<br>8. Avoid duplicate processing<br>9. Support reconciliation</pre><h3>Design</h3><pre>Client<br>  |<br>Payment API<br>  |<br>Database: payment table with idempotency key<br>  |<br>Kafka: payment-events<br>  |<br>  |-- Fraud Service<br>  |-- Ledger Service<br>  |-- Notification Service<br>  |-- Reconciliation Service</pre><h3>Event flow</h3><pre>PAYMENT_INITIATED<br>PAYMENT_VALIDATED<br>FRAUD_CHECK_COMPLETED<br>PAYMENT_AUTHORIZED<br>LEDGER_POSTED<br>PAYMENT_COMPLETED<br>PAYMENT_FAILED</pre><h3>Key design decisions</h3><p>AreaDesignMessage keypaymentIdDuplicate preventionIdempotency key + processed event tableOrderingSame payment ID goes to same partitionRetryExponential backoffDLQFailed messages after max retriesSchemaSchema Registry / versioned eventsMonitoringConsumer lag, DLQ count, payment failure rateAuditStore event metadata and status transitionsReconciliationCompare payment DB, ledger DB, Kafka events</p><h3>Good interview explanation</h3><blockquote><em>I would keep the payment API synchronous only for request acceptance and initial validation. Long-running steps like fraud, ledger posting, notification, and reconciliation can be asynchronous using Kafka.</em></blockquote><blockquote><em>Each event would include </em><em>paymentId, </em><em>eventId, </em><em>correlationId, </em><em>eventType, timestamp, and version. Consumers would be idempotent and transactional. Failed messages would go through retry and DLQ.</em></blockquote><blockquote><em>For financial correctness, I would not depend only on Kafka delivery semantics. I would use database constraints, processed-event tracking, audit tables, and reconciliation jobs.</em></blockquote><h3>15. Must-know Kafka terms</h3><p>TermSimple MeaningBrokerKafka serverTopicStream/category of messagesPartitionUnit of parallelism and orderingOffsetMessage position in partitionProducerSends messagesConsumerReads messagesConsumer groupGroup of consumers sharing workRebalancePartition reassignment among consumersRetentionHow long Kafka stores messagesReplication factorNumber of broker copiesLeader partitionBroker handling reads/writes for partitionISRIn-sync replicasDLQ / DLTDead-letter queue/topicConsumer lagDifference between latest offset and consumed offsetSchema RegistryManages message schema compatibility</p><h3>16. Quick mock interview Q&amp;A</h3><h3>Q1. Why use Kafka in microservices?</h3><blockquote><em>Kafka decouples microservices and allows asynchronous communication. It improves scalability, resilience, and replayability. In payment systems, Kafka allows payment, fraud, ledger, notification, and reconciliation services to process events independently.</em></blockquote><h3>Q2. Does Kafka guarantee ordering?</h3><blockquote><em>Kafka guarantees ordering only within a partition. To maintain order for a business entity like payment, we should use the same key, such as </em><em>paymentId, so all related events go to the same partition.</em></blockquote><h3>Q3. Can Kafka lose messages?</h3><blockquote><em>Kafka can be configured for strong durability using replication, </em><em>acks=all, proper </em><em>min.insync.replicas, and idempotent producer. But poor configuration such as </em><em>acks=0, low replication, or committing offsets too early can cause message loss from the application perspective.</em></blockquote><h3>Q4. Why do duplicates happen in Kafka?</h3><blockquote><em>Duplicates can happen due to retries, consumer crash before offset commit, rebalance, producer retry, or replay. Kafka consumers should be idempotent, especially in payment systems.</em></blockquote><h3>Q5. How do you handle poison messages?</h3><blockquote><em>A poison message repeatedly fails processing. I would retry with backoff for transient failures. For non-recoverable failures, I would send it to DLQ with failure metadata and alert the team.</em></blockquote><h3>Q6. What is consumer lag?</h3><blockquote><em>Consumer lag is the difference between the latest offset in Kafka and the last offset processed by the consumer. High lag means consumers are falling behind.</em></blockquote><h3>Q7. How do you reduce consumer lag?</h3><blockquote><em>Increase consumer instances if partitions allow, increase partitions if needed, optimize processing logic, batch DB writes, reduce downstream latency, tune poll settings, and handle retries separately so they do not block normal processing.</em></blockquote><h3>Q8. What is the role of replication factor?</h3><blockquote><em>Replication factor defines how many copies of a partition exist across brokers. If replication factor is 3, Kafka keeps three copies for fault tolerance.</em></blockquote><h3>Q9. What is ISR?</h3><blockquote><em>ISR means in-sync replicas. These are replicas that are fully caught up with the leader. For strong durability, producers with </em><em>acks=all wait for acknowledgement from in-sync replicas.</em></blockquote><h3>Q10. What is retention?</h3><blockquote><em>Retention controls how long Kafka keeps messages. Kafka does not immediately delete messages after consumption. This allows replay and multiple consumer groups.</em></blockquote><h3>17. Your strong senior-level Kafka answer</h3><p>Use this when interviewer asks, “How have you used Kafka?”</p><blockquote><em>In my microservices architecture, Kafka was used for event-driven communication between payment-related services. For example, when a payment was initiated, the payment service published a payment event to Kafka. Downstream services such as fraud, ledger, notification, and reconciliation consumed those events using separate consumer groups.</em></blockquote><blockquote><em>We used Kafka keys like </em><em>paymentId to maintain ordering for the same transaction. Consumers were designed to be idempotent using event IDs and database constraints to avoid duplicate processing. For failures, we used retry with backoff and dead-letter topics.</em></blockquote><blockquote><em>From a production standpoint, we monitored consumer lag, DLQ count, processing latency, and failure rate. For deployment on Kubernetes, we ensured graceful shutdown so consumers could finish processing and commit offsets safely before termination.</em></blockquote><h3>18. Most important things to remember for Product Based Company-style interview</h3><p>These are your money lines:</p><blockquote><em>Kafka provides ordering within a partition, not across the entire topic.</em></blockquote><blockquote><em>Consumer group parallelism is limited by the number of partitions.</em></blockquote><blockquote><em>Kafka can redeliver messages, so consumers must be idempotent.</em></blockquote><blockquote><em>For payment systems, exactly-once should be treated carefully. Kafka exactly-once does not automatically cover database updates or external APIs.</em></blockquote><blockquote><em>DLQ should include failure reason, original topic, partition, offset, event ID, and correlation ID.</em></blockquote><blockquote><em>Consumer lag tells us whether downstream processing is keeping up.</em></blockquote><blockquote><em>For financial systems, auditability and reconciliation are just as important as message delivery.</em></blockquote><h3>19. 3-day Kafka preparation plan</h3><h3>Day 1: Core concepts</h3><p>Focus on:</p><pre>Topic<br>Partition<br>Offset<br>Producer<br>Consumer<br>Consumer group<br>Broker<br>Replication<br>Retention</pre><p>Practice explaining each in simple language.</p><h3>Day 2: Reliability and failures</h3><p>Focus on:</p><pre>At-least-once<br>At-most-once<br>Exactly-once<br>Idempotency<br>Retry<br>DLQ<br>Offset commit<br>Consumer crash<br>Rebalance</pre><p>Practice payment duplicate scenarios.</p><h3>Day 3: Senior scenarios</h3><p>Focus on:</p><pre>Consumer lag<br>Ordering issue<br>Duplicate ledger entry<br>Kafka + Kubernetes<br>Schema evolution<br>Payment event design<br>Monitoring<br>Production troubleshooting</pre><h3>20. Final practice question for you</h3><p>Practice answering this aloud:</p><blockquote><em>A payment event is consumed twice by the ledger service, and two ledger entries are created. How would you debug and fix this?</em></blockquote><p>Best answer structure:</p><pre>1. Confirm duplicate event using eventId/paymentId/correlationId<br>2. Check Kafka offset, consumer restart, rebalance, retry logs<br>3. Check whether offset was committed after processing<br>4. Check if consumer is idempotent<br>5. Add processed_event table<br>6. Add DB unique constraint<br>7. Use transaction around ledger insert + processed event insert<br>8. Improve monitoring for duplicate attempts<br>9. Replay safely if needed</pre><p>Final polished answer:</p><blockquote><em>I would first confirm whether the duplicate came from Kafka redelivery, producer retry, manual replay, or application retry. Then I would check consumer logs, offset commits, rebalance events, and Kubernetes Pod restarts.</em></blockquote><blockquote><em>To fix it permanently, I would make the ledger consumer idempotent. Each event should have a unique </em><em>eventId, and before creating a ledger entry, the service should check whether that event was already processed. I would also enforce a database unique constraint so even if the same message is consumed twice, duplicate ledger entries cannot be created.</em></blockquote><blockquote><em>For payments, this is critical because Kafka may provide at-least-once delivery, but the business requirement is effectively-once financial posting.</em></blockquote><p><a href="https://dildeepak.medium.com/case-study-system-design-round-for-banking-tech-giant-012928eb256e">Case study / System Design Round for Banking Tech Giant</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15202727bee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Core and Spring Boot Interview Questions for Experienced Professional]]></title>
            <link>https://dildeepak.medium.com/spring-core-and-spring-boot-interview-questions-for-experienced-professional-75b18da2a176?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/75b18da2a176</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 05:09:22 GMT</pubDate>
            <atom:updated>2026-06-15T05:09:22.235Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What is Spring Framework?</h3><p>Spring is a Java framework used to build enterprise applications. It provides features like dependency injection, aspect-oriented programming, transaction management, MVC, security, and data access.</p><p>In my experience, Spring helps us write loosely coupled code. Instead of creating objects manually, Spring manages object creation and wiring. This makes the application easier to test, maintain, and extend.</p><h3>2. What is IoC in Spring?</h3><p>IoC means <strong>Inversion of Control</strong>. Normally, we create objects ourselves using new. In Spring, the framework creates and manages objects for us.</p><p>For example, instead of creating a repository object inside a service class, Spring injects it automatically. This reduces tight coupling between classes.</p><pre>@Service<br>public class OrderService {</pre><pre>    private final OrderRepository orderRepository;</pre><pre>    public OrderService(OrderRepository orderRepository) {<br>        this.orderRepository = orderRepository;<br>    }<br>}</pre><p>Here, Spring creates OrderRepository and injects it into OrderService.</p><h3>3. What is Dependency Injection?</h3><p>Dependency Injection means providing required dependencies to a class from outside instead of creating them inside the class.</p><p>In Spring Boot projects, I mostly use constructor injection. It makes the code cleaner and easier to test.</p><pre>@Service<br>public class PaymentService {</pre><pre>    private final PaymentClient paymentClient;</pre><pre>    public PaymentService(PaymentClient paymentClient) {<br>        this.paymentClient = paymentClient;<br>    }<br>}</pre><p>This means PaymentService depends on PaymentClient, but it does not create it manually.</p><h3>4. What are the types of Dependency Injection in Spring?</h3><p>There are mainly three types:</p><ol><li>Constructor injection</li><li>Setter injection</li><li>Field injection</li></ol><p>In real projects, constructor injection is preferred because dependencies are final, mandatory, and easy to mock during unit testing.</p><p>Field injection is simple but not recommended for large applications because it hides dependencies and makes testing harder.</p><h3>5. What is a Spring Bean?</h3><p>A Spring Bean is an object managed by the Spring container. When we annotate a class with @Component, @Service, @Repository, or @Controller, Spring creates an object of that class and manages its lifecycle.</p><p>For example:</p><pre>@Service<br>public class UserService {<br>}</pre><p>Here, UserService becomes a Spring Bean.</p><h3>6. What is Bean Scope in Spring?</h3><p>Bean scope defines how many instances of a bean Spring should create.</p><p>Common scopes are:</p><p>ScopeMeaningSingletonOne object per Spring containerPrototypeNew object every time requestedRequestOne object per HTTP requestSessionOne object per HTTP session</p><p>By default, Spring beans are singleton. In most microservices, we use singleton beans for services, controllers, and repositories.</p><h3>7. What is Singleton Scope?</h3><p>Singleton means Spring creates only one object of a bean and reuses it throughout the application.</p><p>For example, a service class is usually singleton:</p><pre>@Service<br>public class AccountService {<br>}</pre><p>This same object is reused for multiple requests. Because of this, we should avoid keeping request-specific data in instance variables inside singleton beans.</p><h3>8. What is Prototype Scope?</h3><p>Prototype scope means Spring creates a new object every time the bean is requested.</p><pre>@Scope(&quot;prototype&quot;)<br>@Component<br>public class ReportGenerator {<br>}</pre><p>This is useful when we need a fresh object with different state each time. But in most REST microservices, we use singleton beans more commonly.</p><h3>9. Difference between @Component, @Service, @Repository, and @Controller</h3><p>All of these create Spring Beans, but they are used for different layers.</p><p>AnnotationUsed For@ComponentGeneric Spring bean@ServiceBusiness logic layer@RepositoryDatabase layer@ControllerMVC controller@RestControllerREST API controller</p><p>In my projects, I usually follow this structure:</p><pre>Controller → Service → Repository</pre><p>This keeps the application clean and maintainable.</p><h3>10. What is @Autowired?</h3><p>@Autowired is used to inject dependencies automatically.</p><p>Earlier, many projects used field injection like this:</p><pre>@Autowired<br>private UserRepository userRepository;</pre><p>But now constructor injection is preferred:</p><pre>private final UserRepository userRepository;</pre><pre>public UserService(UserRepository userRepository) {<br>    this.userRepository = userRepository;<br>}</pre><p>Spring automatically injects the required bean.</p><h3>11. What is @Qualifier?</h3><p>@Qualifier is used when multiple beans of the same type exist, and we want to specify which one should be injected.</p><p>Example:</p><pre>@Component(&quot;emailNotification&quot;)<br>public class EmailNotificationService implements NotificationService {<br>}</pre><pre>@Component(&quot;smsNotification&quot;)<br>public class SmsNotificationService implements NotificationService {<br>}</pre><p>Usage:</p><pre>public AlertService(@Qualifier(&quot;emailNotification&quot;) NotificationService service) {<br>    this.service = service;<br>}</pre><p>Without @Qualifier, Spring may get confused because there are two implementations.</p><h3>12. What is @Primary?</h3><p>@Primary tells Spring which bean should be preferred when multiple beans of the same type are available.</p><pre>@Primary<br>@Component<br>public class EmailNotificationService implements NotificationService {<br>}</pre><p>If no @Qualifier is used, Spring will inject the bean marked as @Primary.</p><h3>13. What is Bean Lifecycle in Spring?</h3><p>Spring Bean lifecycle means the journey of a bean from creation to destruction.</p><p>Basic steps:</p><pre>Object created → Dependencies injected → Initialization → Bean used → Destroyed</pre><p>We can run logic after bean creation using @PostConstruct and cleanup logic using @PreDestroy.</p><pre>@PostConstruct<br>public void init() {<br>    System.out.println(&quot;Bean initialized&quot;);<br>}</pre><pre>@PreDestroy<br>public void destroy() {<br>    System.out.println(&quot;Bean destroyed&quot;);<br>}</pre><h3>14. What is ApplicationContext?</h3><p>ApplicationContext is the Spring container. It creates, configures, and manages Spring Beans.</p><p>It also provides features like event publishing, internationalization, environment properties, and bean lookup.</p><p>In Spring Boot, we usually do not interact with ApplicationContext directly, but internally it manages the full application.</p><h3>15. Difference between BeanFactory and ApplicationContext</h3><p>BeanFactory is the basic Spring container. ApplicationContext is the advanced container.</p><p>BeanFactoryApplicationContextBasic containerAdvanced containerLazy bean loadingEager singleton loading by defaultFewer featuresMore enterprise featuresRarely used directlyCommon in Spring apps</p><p>In Spring Boot applications, ApplicationContext is used.</p><h3>Spring Boot Interview Questions</h3><h3>16. What is Spring Boot?</h3><p>Spring Boot is a framework built on top of Spring that simplifies application development. It provides auto-configuration, embedded servers, starter dependencies, and production-ready features.</p><p>In my projects, I used Spring Boot to create microservices quickly. It helped us expose REST APIs, connect to databases, integrate Kafka, secure APIs, and deploy services easily.</p><h3>17. Why Spring Boot is used for microservices?</h3><p>Spring Boot is commonly used for microservices because each service can run independently with its own embedded server. It also supports externalized configuration, health checks, REST APIs, security, logging, and cloud deployment.</p><p>For example, one microservice can handle payments, another can handle users, and another can handle notifications. Each can be built and deployed independently.</p><h3>18. What is @SpringBootApplication?</h3><p>@SpringBootApplication is the main annotation used in Spring Boot applications.</p><p>It combines three annotations:</p><pre>@SpringBootApplication =<br>@Configuration<br>+ @EnableAutoConfiguration<br>+ @ComponentScan</pre><p>Example:</p><pre>@SpringBootApplication<br>public class PaymentApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(PaymentApplication.class, args);<br>    }<br>}</pre><p>This starts the Spring Boot application.</p><h3>19. What is Auto-Configuration?</h3><p>Auto-configuration means Spring Boot automatically configures required beans based on dependencies present in the classpath.</p><p>For example, if we add:</p><pre>spring-boot-starter-web</pre><p>Spring Boot automatically configures:</p><pre>Tomcat<br>Spring MVC<br>Jackson<br>DispatcherServlet<br>REST support</pre><p>This reduces manual configuration.</p><h3>20. How can you exclude auto-configuration?</h3><p>Sometimes we do not want Spring Boot to configure something automatically. We can exclude it like this:</p><pre>@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)<br>public class MyApplication {<br>}</pre><p>This is useful when we do not want database auto-configuration or want to provide custom configuration.</p><h3>21. What are Spring Boot Starters?</h3><p>Starters are ready-made dependency groups.</p><p>Examples:</p><p>StarterPurposespring-boot-starter-webREST APIsspring-boot-starter-data-jpaJPA/Hibernatespring-boot-starter-securitySecurityspring-boot-starter-testTestingspring-boot-starter-actuatorMonitoring</p><p>Instead of adding many dependencies manually, we add one starter.</p><h3>22. What is embedded server in Spring Boot?</h3><p>Spring Boot comes with embedded servers like Tomcat, Jetty, or Undertow. This means we do not need to deploy a WAR file to an external server.</p><p>We can run the application as a simple JAR:</p><pre>java -jar payment-service.jar</pre><p>This is very useful for microservices and cloud deployment.</p><h3>23. How do you change the default port in Spring Boot?</h3><p>By default, Spring Boot runs on port 8080.</p><p>We can change it in application.properties:</p><pre>server.port=9090</pre><p>Or in application.yml:</p><pre>server:<br>  port: 9090</pre><p>In cloud deployments, port can also be passed through environment variables.</p><h3>24. What is application.properties or application.yml?</h3><p>These files are used to store application configuration.</p><p>Examples:</p><pre>server.port=8081<br>spring.datasource.url=jdbc:mysql://localhost:3306/test<br>logging.level.root=INFO</pre><p>I use these files for database configuration, Kafka config, service URLs, logging levels, and feature flags.</p><h3>25. What are Spring Profiles?</h3><p>Spring Profiles allow us to maintain different configuration for different environments.</p><p>Example:</p><pre>application-dev.yml<br>application-qa.yml<br>application-prod.yml</pre><p>We can activate a profile like this:</p><pre>spring.profiles.active=dev</pre><p>In real projects, this helps us use different databases, URLs, credentials, and logging levels for dev, QA, staging, and production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75b18da2a176" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 30 Spring Boot Interview Questions with Answers for Experienced Java Developer]]></title>
            <link>https://dildeepak.medium.com/top-30-spring-boot-interview-questions-with-answers-for-experienced-java-developer-764e9172239d?source=rss-f4faf5ec48e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/764e9172239d</guid>
            <dc:creator><![CDATA[Dilip Kumar Jha ]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 18:39:08 GMT</pubDate>
            <atom:updated>2026-07-30T04:36:06.342Z</atom:updated>
            <content:encoded><![CDATA[<p>Below are <strong>top 30 Spring Boot interview questions with human-style answers</strong>, tailored to your experience as a <strong>Senior Java Backend Developer working with Spring Boot, REST APIs, microservices, Kafka, cloud deployment, OAuth/JWT, JUnit, monitoring, and production support</strong>.</p><h3>1. What is Spring Boot and why did you use it?</h3><p>Spring Boot is a framework built on top of Spring that helps us create production-ready applications quickly. In my projects, I used Spring Boot mainly to build REST-based microservices. It reduces boilerplate configuration through auto-configuration, embedded servers, starters, and externalized configuration. For example, instead of manually configuring Tomcat and dependencies, I used spring-boot-starter-web and created REST APIs directly. It helped our team develop, test, and deploy services faster.</p><h3>2. What are the main advantages of Spring Boot?</h3><p>The main advantages are auto-configuration, embedded server support, starter dependencies, production-ready Actuator endpoints, and easy integration with cloud and monitoring tools. In my experience, Spring Boot made microservice development much easier because each service could run independently with its own embedded Tomcat. It also helped with health checks, metrics, and environment-specific configuration using profiles.</p><h3>3. What is auto-configuration in Spring Boot?</h3><p>Auto-configuration means Spring Boot automatically configures beans based on the dependencies available in the classpath. For example, when we add spring-boot-starter-web, Spring Boot automatically configures DispatcherServlet, Jackson, embedded Tomcat, and REST support. In my projects, this reduced a lot of manual XML or Java configuration. But when needed, we could still override the default behavior by defining our own bean.</p><h3>4. What is the difference between Spring and Spring Boot?</h3><p>Spring is the core framework that provides dependency injection, AOP, transaction management, MVC, and other features. Spring Boot is an extension of Spring that simplifies application setup and deployment. In Spring, we usually need more manual configuration. In Spring Boot, we get auto-configuration, embedded server, starters, and Actuator support. In real projects, I mostly worked with Spring Boot because it is better suited for microservices.</p><h3>5. What is @SpringBootApplication?</h3><p>@SpringBootApplication is a combination of three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan. It marks the main class of a Spring Boot application. In my services, this annotation was used in the main class to bootstrap the application. It also scans components like controllers, services, repositories, and configuration classes from the base package.</p><h3>6. How does a request flow in a Spring Boot REST API?</h3><p>In my project, the request first hits the controller layer through a REST endpoint. The controller validates the request and passes it to the service layer. The service layer contains the business logic and may call repositories, external APIs, Kafka producers-consumers, or other microservices. The repository layer interacts with the database. Finally, the response is returned back through the controller, usually as JSON.</p><p>Example flow:</p><pre>Client → Controller → Service → Repository / External API / Kafka → Response</pre><h3>7. What is the role of Controller, Service, and Repository?</h3><p>The controller handles HTTP requests and responses. The service layer contains business logic. The repository layer handles database operations. I usually keep controllers lightweight and put most logic in the service layer. This makes the code easier to test and maintain. For example, in a payment or transaction service, the controller receives the request, the service validates and processes it, and the repository saves or fetches transaction data.</p><h3>8. What is dependency injection?</h3><p>Dependency injection is a design pattern where Spring creates and injects required objects instead of us creating them manually using new. In my project, I used constructor injection mostly because it makes dependencies mandatory and helps with unit testing. For example, a service class can receive a repository or Kafka producer through its constructor. This keeps the code loosely coupled and easier to mock in JUnit tests.</p><h3>9. Which injection do you prefer: field injection or constructor injection?</h3><p>I prefer constructor injection. It is cleaner, better for unit testing, and makes required dependencies clear. Field injection using @Autowired works, but it hides dependencies and makes testing harder. With constructor injection, I can easily pass mock objects during JUnit testing. In production code, this also helps avoid null dependency issues.</p><h3>10. What are Spring Boot starters?</h3><p>Starters are dependency packages that group commonly used libraries together. For example, spring-boot-starter-web includes Spring MVC, Jackson, validation support, and embedded Tomcat. spring-boot-starter-data-jpa includes JPA and Hibernate-related dependencies. In my projects, starters helped reduce dependency management effort and made setup faster.</p><h3>11. What is Spring Boot Actuator?</h3><p>Spring Boot Actuator provides production-ready endpoints for monitoring and managing applications. I have used Actuator endpoints like /actuator/health, /actuator/metrics, and /actuator/info. These are useful in cloud or Kubernetes environments because health endpoints can be used for readiness and liveness checks. It also helps support teams monitor application status without checking logs manually.</p><h3>12. How do you handle exceptions in Spring Boot?</h3><p>I usually handle exceptions globally using @ControllerAdvice and @ExceptionHandler. This allows us to return consistent error responses across all APIs. For example, validation errors, business exceptions, database errors, and external service failures can all be converted into proper HTTP responses. This approach avoids writing repeated try-catch blocks in every controller.</p><p>Example:</p><pre>@ControllerAdvice<br>public class GlobalExceptionHandler {</pre><pre>    @ExceptionHandler(ResourceNotFoundException.class)<br>    public ResponseEntity&lt;String&gt; handleNotFound(ResourceNotFoundException ex) {<br>        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());<br>    }<br>}</pre><h3>13. How do you validate request data in Spring Boot?</h3><p>I use Bean Validation annotations like @NotNull, @NotBlank, @Email, @Size, and @Pattern in request DTOs. In the controller, I use @Valid to trigger validation. If validation fails, Spring throws an exception, which we handle globally using @ControllerAdvice. This keeps validation clean and consistent.</p><p>Example:</p><pre>public class UserRequest {<br>    @NotBlank<br>    private String name;</pre><pre>    @Email<br>    private String email;<br>}</pre><h3>14. What is the difference between @Component, @Service, and @Repository?</h3><p>All three are Spring stereotypes and create Spring-managed beans. @Component is generic. @Service is used for business logic classes. @Repository is used for database-related classes and also helps translate persistence exceptions. In my projects, I used @RestController for APIs, @Service for business logic, and @Repository for database access.</p><h3>15. What is the difference between @RestController and @Controller?</h3><p>@Controller is mainly used for MVC applications where we return views like JSP or Thymeleaf pages. @RestController is used for REST APIs and automatically converts return objects into JSON or XML using @ResponseBody. In my backend microservices, I mostly used @RestController because the services exposed REST endpoints consumed by frontend apps or other microservices.</p><h3>16. How do you call one microservice from another?</h3><p>In my projects, microservices communicated using REST APIs or asynchronous messaging like Kafka. For synchronous communication, we used REST clients such as RestTemplate, WebClient, or Feign Client depending on the project. For asynchronous communication, we used Kafka when we did not want one service to block another. For example, after a transaction is processed, we can publish an event to Kafka and another service can consume it.</p><h3>17. What is the difference between synchronous and asynchronous communication?</h3><p>Synchronous communication means one service calls another and waits for the response, like REST API calls. It is simple but creates dependency between services. Asynchronous communication means one service sends a message to Kafka or a queue and continues without waiting. This improves scalability and resilience. In my experience, REST is good when immediate response is needed, while Kafka is better for event-driven processing, notifications, audit logs, or downstream updates.</p><h3>18. How did you use Kafka with Spring Boot?</h3><p>I used Kafka with Spring Boot for event-driven communication between microservices. One service produces events to a topic, and another service consumes those events. For example, after a payment or transaction update, we can publish an event to Kafka so downstream services can process it independently. In Spring Boot, we can use KafkaTemplate for producing messages and @KafkaListener for consuming messages.</p><p>Example:</p><pre>kafkaTemplate.send(&quot;transaction-topic&quot;, transactionEvent);</pre><h3>19. How do you secure Spring Boot APIs?</h3><p>I secured APIs using Spring Security with OAuth2 and JWT tokens. The client sends a JWT token in the Authorization header. The API validates the token, checks claims or roles, and then allows or denies access. In enterprise projects, authentication can be handled by providers like Okta or another identity provider, while Spring Boot services validate the token before processing the request.</p><h3>20. What is JWT and how does it work in Spring Boot?</h3><p>JWT stands for JSON Web Token. It contains user identity and claims in a signed token. In Spring Boot, when a request comes with a Bearer token, the security filter validates the token signature, expiration, issuer, and roles. If valid, Spring Security creates an authentication object and allows the request. I used this pattern to secure REST APIs in microservices.</p><h3>21. What are filters and interceptors in Spring Boot?</h3><p>Filters work at the servlet level and execute before the request reaches Spring MVC. Interceptors work at the Spring MVC level, before and after controller execution. In my experience, filters are useful for security, request logging, correlation IDs, and header validation. Interceptors are useful for application-level checks, audit logging, or modifying request/response behavior around controller calls.</p><h3>22. How do you implement logging in Spring Boot microservices?</h3><p>I usually use SLF4J with Logback. In microservices, structured logging is important. I include details like correlation ID, request ID, service name, transaction ID, and error details. This helps trace requests across multiple services. Logs can then be sent to tools like Splunk, Cloud Logging, ELK, or other monitoring platforms. For production issues, correlation IDs are very useful because one request may travel across multiple services.</p><h3>23. How do you handle distributed tracing?</h3><p>For distributed tracing, I use correlation IDs and tracing tools such as Sleuth/Micrometer tracing, Zipkin, Jaeger, OpenTelemetry, or cloud-native tracing depending on the environment. The main idea is to pass a trace ID from one service to another so we can track the full request path. This helps in troubleshooting latency, timeout, and failure issues across multiple microservices.</p><h3>24. How do you handle external API failure in Spring Boot?</h3><p>For external API failures, I usually apply timeout, retry, fallback, and circuit breaker patterns. We should not allow one slow downstream service to bring down the whole application. In Spring Boot, Resilience4j can be used for retry and circuit breaker. I also log the error with proper context and return a meaningful response to the client. For critical flows, failed events can be pushed to Kafka or a retry queue.</p><h3>25. What is Circuit Breaker pattern?</h3><p>Circuit Breaker is used to stop repeated calls to a failing service. If a downstream service is failing continuously, the circuit opens and stops sending requests for some time. After a configured time, it allows limited calls to check if the service recovered. I used this concept to protect microservices from cascading failures. It improves system resilience and avoids unnecessary load on failing services.</p><h3>26. How do you write unit tests in Spring Boot?</h3><p>I write unit tests using JUnit and Mockito. For service classes, I mock dependencies like repositories, REST clients, or Kafka producers and test only the business logic. For controller testing, I use MockMvc. My approach is to cover positive scenarios, negative scenarios, validation failures, exception handling, and edge cases. This helps improve code coverage and confidence before deployment.</p><p>Example:</p><pre>@Mock<br>private UserRepository userRepository;</pre><pre>@InjectMocks<br>private UserService userService;</pre><h3>27. What is the difference between unit testing and integration testing?</h3><p>Unit testing tests a single class or method by mocking its dependencies. Integration testing tests multiple layers together, like controller, service, repository, and database interaction. In my projects, I used unit tests for business logic and integration tests for APIs, database operations, and end-to-end flows. Unit tests are faster, while integration tests give more confidence about actual application behavior.</p><h3>28. How do you manage configuration in Spring Boot?</h3><p>I use application.properties or application.yml for configuration. For different environments, I use Spring profiles like dev, qa, stage, and prod. Sensitive values like passwords, tokens, or keys should not be stored directly in code. In cloud environments, these can be managed using Secret Manager, Kubernetes secrets, environment variables, or vault-based solutions.</p><p>Example:</p><pre>spring:<br>  profiles:<br>    active: dev</pre><h3>29. What are Spring profiles?</h3><p>Spring profiles allow us to load different configurations for different environments. For example, local development may use one database, QA may use another, and production may use a secured cloud database. In my projects, profiles helped us keep environment-specific properties separate without changing the code. We could activate profiles through environment variables or deployment configuration.</p><h3>30. How do you deploy Spring Boot microservices?</h3><p>In my experience, Spring Boot services are usually packaged as JAR files, containerized using Docker, and deployed to cloud platforms like GCP, Kubernetes, Cloud Run, or similar environments. The CI/CD pipeline builds the code, runs tests, creates a Docker image, pushes it to a registry, and deploys it. Health checks from Actuator are used to make sure the service is ready and healthy after deployment.</p><p>Typical flow:</p><pre>Code Commit → Build → Unit Test → Docker Image → Registry → Deploy → Health Check</pre><h3>Strong closing answer for interview</h3><p>You can say:</p><blockquote><em>“Most of my Spring Boot experience is around building RESTful microservices using layered architecture — controller, service, repository. I have worked on securing APIs with OAuth/JWT, integrating services using REST and Kafka, handling exceptions globally, writing JUnit/Mockito tests, and deploying services in cloud environments. I also focus on production readiness using proper logging, Actuator health checks, monitoring, and resilience patterns like retry and circuit breaker.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=764e9172239d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>