<?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 Rajat Sharma on Medium]]></title>
        <description><![CDATA[Stories by Rajat Sharma on Medium]]></description>
        <link>https://medium.com/@rajatmtr30?source=rss-7faa42c577df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PEPfd5glqVo-W7MJ</url>
            <title>Stories by Rajat Sharma on Medium</title>
            <link>https://medium.com/@rajatmtr30?source=rss-7faa42c577df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:24:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajatmtr30/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[Authentication Explained: Basic Auth, Sessions, JWT, OAuth 2.0, OIDC & SSO]]></title>
            <link>https://medium.com/@rajatmtr30/authentication-explained-basic-auth-sessions-jwt-oauth-2-0-oidc-sso-4694bfb850b0?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/4694bfb850b0</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 07:46:04 GMT</pubDate>
            <atom:updated>2026-09-21T07:46:04.453Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have worked with backend APIs, you have probably come across terms like <strong>Basic Authentication, API Keys, Sessions, JWT, Bearer Tokens, OAuth 2.0, OpenID Connect, and SSO</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1QmRDJl6RX9PU9GcOiAxw.png" /></figure><p>The confusing part is that these terms are often used as if they all mean the same thing.</p><p>For example:</p><ul><li><strong>JWT</strong> is a token format.</li><li><strong>Bearer</strong> describes how a token is presented.</li><li><strong>OAuth 2.0</strong> is an authorization framework.</li><li><strong>OpenID Connect</strong> adds authentication on top of OAuth 2.0.</li><li><strong>SSO</strong> is a login experience/pattern.</li><li><strong>API keys</strong> are commonly used for API or service access.</li><li><strong>Sessions</strong> are a stateful way of maintaining authentication.</li></ul><p>Once you understand this distinction, authentication becomes much easier to reason about.</p><p>Let’s break it down from the basics.</p><h4>First: What Exactly Is Authentication?</h4><p>Authentication answers one simple question:</p><blockquote><strong><em>Who are you?</em></strong></blockquote><p>Imagine a typical backend system:</p><pre>Client<br>   |<br>   v<br>API Gateway<br>   |<br>   v<br>Backend Services<br>   |<br>   v<br>Database</pre><p>A client shouldn’t simply be allowed to call every API.</p><p>Before accessing protected resources, the system needs to verify the identity of the requester.</p><pre>Client<br>   |<br>   | Login credentials<br>   v<br>Authentication Server<br>   |<br>   | Identity verified<br>   v<br>Access to APIs</pre><p>If the identity cannot be verified, the server can reject the request with:</p><pre>401 Unauthorized</pre><p>But authentication is only the first step.</p><p>Once we know <strong>who you are</strong>, we need to answer another question:</p><blockquote><strong><em>What are you allowed to do?</em></strong></blockquote><p>That’s authorization.</p><p>So remember:</p><pre>Authentication → Who are you?</pre><pre>Authorization → What can you do?</pre><p>This distinction is extremely important when designing APIs and microservices.</p><h3>1. Basic Authentication</h3><p>Let’s start with the simplest approach: <strong>Basic Authentication</strong>.</p><p>The client sends a username and password with the request.</p><p>For example:</p><pre>GET /api/users<br>Authorization: Basic &lt;credentials&gt;</pre><p>The credentials are Base64 encoded before being sent.</p><p>Something important to remember:</p><blockquote><strong><em>Base64 is encoding, not encryption.</em></strong></blockquote><p>It can easily be decoded.</p><p>That’s why Basic Authentication should always be used over <strong>HTTPS</strong>.</p><p>The basic flow looks like this:</p><pre>Client<br>   |<br>   | Username + Password<br>   v<br>Server<br>   |<br>   | Validate credentials<br>   |<br>   +---- Valid ----&gt; 200 OK<br>   |<br>   +---- Invalid --&gt; 401 Unauthorized</pre><p>Basic Authentication is simple, but it isn’t commonly chosen for modern consumer applications.</p><p>You may still encounter it in:</p><ul><li>Internal tools</li><li>Simple APIs</li><li>Legacy applications</li><li>Development environments</li></ul><h3>2. Digest Authentication</h3><p>Digest Authentication was introduced as an improvement over Basic Authentication.</p><p>Instead of sending the password directly, the client sends a digest calculated from the credentials and request information.</p><p>Historically, this involved MD5.</p><p>The idea looks roughly like:</p><pre>Username + Password + Request Data<br>                |<br>                v<br>              Hash<br>                |<br>                v<br>             Server</pre><p>The server can then verify the digest.</p><p>It is better than simply sending credentials in an easily reversible encoding, but it is now considered an older approach.</p><p>Modern applications generally have better alternatives.</p><h3>3. API Key Authentication</h3><p>If you’ve ever used a third-party API, you’ve probably seen an API key.</p><p>You generate a key from the provider’s dashboard and then send that key with your API requests.</p><p>For example:</p><pre>GET /api/users<br>X-API-Key: abc123xyz</pre><p>The server receives the key and checks whether it is valid.</p><p>A simplified flow:</p><pre>Client<br>   |<br>   | API Key<br>   v<br>API Server<br>   |<br>   | Validate key<br>   v<br>Database / Cache<br>   |<br>   +---- Valid ----&gt; Allow request<br>   |<br>   +---- Invalid --&gt; 401</pre><p>API keys are commonly used for:</p><ul><li>Public APIs</li><li>Developer integrations</li><li>Server-to-server communication</li><li>Third-party services</li></ul><h4>The problem with API keys</h4><p>The biggest problem is what happens if the key leaks.</p><p>Anyone who gets the key may be able to use it.</p><p>That’s why production systems often support:</p><ul><li>Key rotation</li><li>Expiration</li><li>Revocation</li><li>Scopes</li><li>Rate limits</li><li>Hashing</li><li>Secret management</li></ul><p>Another important characteristic is that an API key usually doesn’t contain user information.</p><p>The server typically has to look it up to understand:</p><pre>Who owns this key?<br>What can it access?<br>Is it still valid?</pre><h3>4. Session-Based Authentication</h3><p>This is the classic approach used by many traditional web applications.</p><p>The user logs in:</p><pre>Username + Password<br>        |<br>        v<br>      Server<br>        |<br>        v<br> Create Session<br>        |<br>        v<br>   Session Store<br>        |<br>        v<br>   Session ID<br>        |<br>        v<br>     Browser</pre><p>The browser receives a session cookie.</p><pre>Cookie: sessionId=abc123</pre><p>Every subsequent request sends that cookie.</p><p>The server then looks up the session:</p><pre>Session ID<br>    |<br>    v<br>Session Store<br>    |<br>    v<br>User Information</pre><p>If the session exists and is valid, the request is authenticated.</p><h4>Where do we store sessions?</h4><p>There are several options.</p><h4>In-memory</h4><p>You can store sessions directly in application memory.</p><p>It’s simple, but there is an obvious problem:</p><pre>Server Restart<br>      |<br>      v<br>Sessions Lost</pre><p>It’s also difficult when you have multiple application instances.</p><h4>Database</h4><p>Sessions can be stored in a database.</p><p>This works, but repeatedly accessing the database for session validation can add overhead.</p><h4>Redis</h4><p>Redis is a popular choice for production systems.</p><p>For example:</p><pre>┌── Application 1<br>Client ──────┼── Application 2<br>             └── Application 3<br>                     |<br>                     v<br>                   Redis<br>                     |<br>                  Sessions</pre><p>All application instances can access the same session store.</p><p>Redis also provides fast access and expiration support.</p><h4>The main characteristic of sessions</h4><p>Sessions are <strong>stateful</strong>.</p><p>The server needs to remember something about the client.</p><p>That’s perfectly fine for many traditional web applications.</p><p>But when you’re building large distributed systems, you may want an authentication mechanism that doesn’t require a central session lookup for every request.</p><p>That’s where tokens become interesting.</p><h3>5. Bearer Tokens</h3><p>You’ll often see this in API requests:</p><pre>Authorization: Bearer &lt;token&gt;</pre><p>Here’s where another common misunderstanding happens.</p><p><strong>Bearer is not JWT.</strong></p><p>Bearer simply describes how the token is presented.</p><p>The idea is:</p><blockquote><em>Whoever possesses the bearer token can use it.</em></blockquote><p>The token itself could have different formats.</p><p>One very common format is JWT.</p><pre>Bearer → Token presentation method</pre><pre>JWT → Token format</pre><p>This distinction is worth remembering.</p><h3>6. JWT — JSON Web Token</h3><p>JWT stands for <strong>JSON Web Token</strong>.</p><p>A JWT typically looks like:</p><pre>xxxxx.yyyyy.zzzzz</pre><p>It contains three parts:</p><pre>Header.Payload.Signature</pre><p>The payload can contain claims such as:</p><pre>{<br>  &quot;sub&quot;: &quot;12345&quot;,<br>  &quot;email&quot;: &quot;user@example.com&quot;,<br>  &quot;exp&quot;: 1780000000,<br>  &quot;role&quot;: &quot;USER&quot;<br>}</pre><p>The token is signed so the receiving service can verify that it hasn’t been modified.</p><p>A simplified flow looks like this:</p><pre>User Login<br>    |<br>    v<br>Authentication Server<br>    |<br>    | Generate JWT<br>    v<br>Client<br>    |<br>    | Authorization: Bearer JWT<br>    v<br>API<br>    |<br>    | Verify signature<br>    v<br>Allow / Reject</pre><p>One of the biggest advantages of JWT-based authentication is that the token can be <strong>self-contained</strong>.</p><p>The server can often validate the signature and read the claims without looking up a session in a database for every request.</p><p>That makes JWT particularly useful in distributed and microservice architectures.</p><h4>JWT vs Session</h4><p>The difference becomes clearer when we put them side by side.</p><h4>Session</h4><pre>Request<br>   |<br>   v<br>Session ID<br>   |<br>   v<br>Session Store<br>   |<br>   v<br>User</pre><h4>JWT</h4><pre>Request<br>   |<br>   v<br>JWT<br>   |<br>   v<br>Verify Signature<br>   |<br>   v<br>User Claims</pre><p>The first approach depends on server-side state.</p><p>The second can be largely stateless.</p><p>But that doesn’t automatically mean JWT is always better.</p><p>The right choice depends on the architecture, security requirements, client type, and operational needs.</p><h3>7. Access Tokens and Refresh Tokens</h3><p>Modern authentication systems commonly separate tokens into two categories:</p><pre>Access Token<br>Refresh Token</pre><p>They have different responsibilities.</p><h4>Access Token</h4><p>The access token is used to access protected APIs.</p><p>It is usually short-lived.</p><pre>15 minutes<br>30 minutes<br>1 hour</pre><p>The exact lifetime depends on the application.</p><pre>GET /api/orders</pre><pre>Authorization: Bearer &lt;access-token&gt;</pre><h4>Refresh Token</h4><p>Eventually the access token expires.</p><p>Instead of forcing the user to log in again, the application can use a refresh token to obtain a new access token.</p><p>The flow looks like:</p><pre>Login<br>  |<br>  +------&gt; Access Token<br>  |<br>  +------&gt; Refresh Token<br>               |<br>               |<br>          Access expires<br>               |<br>               v<br>        Refresh Token<br>               |<br>               v<br>        New Access Token</pre><p>This gives us a useful balance:</p><ul><li>Access tokens can be short-lived.</li><li>Users don’t have to repeatedly enter credentials.</li></ul><p>For browser applications, refresh tokens are commonly protected using mechanisms such as <strong>HttpOnly cookies</strong>, along with appropriate CSRF protections.</p><h3>8. OAuth 2.0</h3><p>Now we get to one of the most misunderstood terms in authentication.</p><blockquote><strong><em>OAuth 2.0 is an authorization framework.</em></strong></blockquote><p>It is not, by itself, an authentication protocol.</p><p>Think about this example.</p><p>You have an application that wants to access your Google Drive.</p><p>You don’t want to give that application your Google password.</p><p>Instead, you authorize the application to access specific Google Drive resources.</p><p>A simplified flow looks like:</p><pre>User<br> |<br> v<br>Application<br> |<br> | Redirect<br> v<br>Authorization Server<br> |<br> | User gives consent<br> v<br>Authorization Code<br> |<br> v<br>Application<br> |<br> | Exchange code<br> v<br>Access Token<br> |<br> v<br>Google Drive API</pre><p>The access token represents the permissions granted to the application.</p><p>So OAuth is primarily answering:</p><blockquote><strong><em>What can this application access?</em></strong></blockquote><p>Not:</p><blockquote><strong><em>Who is the user?</em></strong></blockquote><p>That’s where OpenID Connect comes in.</p><h3>9. OpenID Connect — OIDC</h3><p>OpenID Connect adds an identity layer on top of OAuth 2.0.</p><p>This is why it is commonly used for modern “Sign in with…” experiences.</p><p>For example:</p><pre>Sign in with Google<br>Sign in with Microsoft<br>Sign in with GitHub</pre><p>A simplified flow:</p><pre>User<br> |<br> v<br>Application<br> |<br> v<br>Identity Provider<br> |<br> | Login<br> | Consent<br> v<br>Authorization Code<br> |<br> v<br>Application<br> |<br> +---- Access Token<br> |<br> +---- ID Token</pre><p>The important new concept here is the <strong>ID Token</strong>.</p><p>The ID token is typically a JWT containing identity-related claims.</p><p>For example:</p><pre>{<br>  &quot;sub&quot;: &quot;12345&quot;,<br>  &quot;email&quot;: &quot;user@example.com&quot;,<br>  &quot;name&quot;: &quot;Rajat&quot;<br>}</pre><p>The application can validate the ID token and use it to establish the user’s identity.</p><p>So a useful mental model is:</p><pre>OAuth 2.0<br>    ↓<br>Authorization<br>    ↓<br>&quot;What can this application access?&quot;</pre><pre>OpenID Connect<br>    ↓<br>Authentication + OAuth 2.0<br>    ↓<br>&quot;Who is this user?&quot;</pre><h3>10. Single Sign-On — SSO</h3><p>Single Sign-On, or SSO, is another concept that is often placed in the wrong category.</p><p>SSO isn’t a specific authentication method.</p><p>It’s a <strong>user experience and identity architecture pattern</strong>.</p><blockquote><em>Log in once and access multiple applications without logging in separately to each one.</em></blockquote><p>For example, imagine an organization with:</p><pre>Employee<br>   |<br>   v<br>Identity Provider<br>   |<br>   +---- HR Application<br>   |<br>   +---- Email<br>   |<br>   +---- Internal Dashboard<br>   |<br>   +---- CRM<br>   |<br>   +---- Developer Portal</pre><p>The user authenticates with the identity provider.</p><p>Other applications trust that identity provider.</p><p>As a result, the user doesn’t have to enter credentials separately into every application.</p><h3>11. SAML</h3><p>SAML stands for:</p><p><strong>Security Assertion Markup Language</strong></p><p>It is an identity protocol that has been widely used for enterprise Single Sign-On.</p><p>SAML uses XML-based assertions.</p><p>A simplified flow is:</p><pre>User<br> |<br> v<br>Application<br> |<br> | Redirect<br> v<br>Identity Provider<br> |<br> | Authenticate<br> v<br>SAML Assertion<br> |<br> v<br>Application<br> |<br> v<br>User authenticated</pre><p>SAML is still widely used in enterprise environments and older systems.</p><p>You’ll often encounter it when integrating applications with corporate identity providers.</p><h3>12. OpenID Connect vs SAML</h3><p>Both can be used in identity and SSO scenarios, but they come from different technology generations and ecosystems.</p><h4>SAML</h4><pre>XML based<br>Enterprise focused<br>Widely used in existing corporate systems</pre><h4>OpenID Connect</h4><pre>Built on OAuth 2.0<br>JSON/JWT based<br>Common in modern web and mobile applications</pre><p>You may therefore see both technologies in real-world enterprise architectures.</p><h4>The Big Picture</h4><p>At this point, let’s put everything together.</p><pre>Authentication<br>                          |<br>       ┌──────────────────┼──────────────────┐<br>       |                  |                  |<br>   Basic Auth          Sessions            Tokens<br>       |                  |                  |<br>    Digest             Cookies         Bearer Tokens<br>       |                                     |<br>    API Keys                                JWT<br>                                             |<br>                                  Access + Refresh</pre><p>And separately:</p><pre>OAuth 2.0<br>    |<br>    v<br>Authorization<br>    |<br>    v<br>&quot;What can this application access?&quot;</pre><p>While:</p><pre>OpenID Connect<br>    |<br>    v<br>Authentication<br>    |<br>    v<br>&quot;Who is this user?&quot;</pre><p>And:</p><pre>SSO<br> |<br> v<br>One login → Multiple applications<br> |<br> +---- SAML<br> |<br> +---- OpenID Connect</pre><h4>The Most Important Things to Remember</h4><p>If you remember only a few things from this article, remember these:</p><h4>1. Authentication and authorization are different</h4><pre>Authentication → Who are you?</pre><pre>Authorization → What can you do?</pre><h4>2. JWT is not an authentication method</h4><p>JWT is a <strong>token format</strong>.</p><h4>3. Bearer is not JWT</h4><p>Bearer describes how the token is presented.</p><p>JWT describes the token format.</p><h4>4. OAuth 2.0 is not authentication</h4><p>OAuth 2.0 is primarily about <strong>delegated authorization</strong>.</p><h4>5. OpenID Connect adds authentication</h4><p>OIDC uses OAuth 2.0 concepts and adds identity information through the ID token.</p><h4>6. SSO is not an authentication protocol</h4><p>SSO is a way for users to authenticate once and access multiple applications.</p><p>SAML and OIDC can be used underneath SSO.</p><h4>Final Thoughts</h4><p>Authentication can look complicated because we often use many different terms together.</p><p>But once you separate them by their actual purpose, the picture becomes much simpler:</p><pre>WHO ARE YOU?<br>                         |<br>                  Authentication<br>                         |<br>          ┌──────────────┼──────────────┐<br>          |              |              |<br>       Sessions        Tokens        Identity<br>          |              |              |<br>        Cookie        JWT/Bearer       OIDC<br>                                         |<br>                                         v<br>                                      SSO</pre><p>And then there is the next layer:</p><pre>Authentication<br>      |<br>      v<br>Authorization<br>      |<br>      v<br>What can the user/application do?</pre><p>Understanding this distinction is especially important when working with <strong>Spring Boot, microservices, API gateways, distributed systems, and third-party identity providers</strong>.</p><p>Once you understand these building blocks, technologies like Keycloak, Auth0, Okta, Azure AD/Microsoft Entra ID, and Google Identity become much easier to understand because you’re no longer treating them as completely different concepts.</p><p>Authentication is ultimately about establishing identity.</p><p>Authorization is about controlling access.</p><p>Happy Learning</p><p>Rajat Sharma</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4694bfb850b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Senior Java & Spring Boot Interview Questions Explained For Interviews — Part 3]]></title>
            <link>https://medium.com/@rajatmtr30/senior-java-spring-boot-interview-questions-explained-for-interviews-part-3-9cfde9392a2c?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cfde9392a2c</guid>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[bitly]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 03:01:02 GMT</pubDate>
            <atom:updated>2026-06-04T03:01:02.172Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 3: Concurrency, Leadership &amp; System Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UugvL-UXCRUoDS9JXynmA.png" /></figure><h3>21. REST API: What is the difference between Safe and Idempotent operations?</h3><p><strong>Interviewer:</strong><br>Can you explain Safe and Idempotent HTTP methods?</p><p><strong>Candidate:</strong></p><h4>Safe Operations</h4><p>Safe methods do not modify server state.</p><p>Examples:</p><pre>GET<br>HEAD<br>OPTIONS</pre><p>Calling them multiple times should not change the data.</p><h4>Idempotent Operations</h4><p>Repeated execution produces the same result.</p><p>Examples:</p><pre>GET<br>PUT<br>DELETE</pre><p>For example:</p><pre>DELETE /users/10</pre><p>Calling it once or ten times leaves the user deleted.</p><p>Not all idempotent methods are safe.</p><h3>22. Have you worked with threads and concurrency?</h3><p><strong>Interviewer:</strong><br>How do you make applications thread-safe?</p><p><strong>Candidate:</strong></p><p>Yes, in concurrent environments, multiple threads access shared resources simultaneously.</p><p>Common approaches:</p><ul><li>Immutable Objects</li><li>Synchronization</li><li>Concurrent Collections</li><li>Locks</li><li>Atomic Variables</li></ul><p>Example:</p><pre>AtomicInteger counter =<br>        new AtomicInteger();</pre><p>Thread safety means preserving correctness under concurrent execution.</p><h3>23. Have you used locks to achieve thread safety?</h3><p><strong>Interviewer:</strong><br>When would you use locks?</p><p><strong>Candidate:</strong></p><p>Yes, for advanced synchronization requirements.</p><p>Example:</p><pre>Lock lock = new ReentrantLock();</pre><pre>lock.lock();</pre><pre>try {<br>   // critical section<br>}<br>finally {<br>   lock.unlock();<br>}</pre><p>Advantages over synchronized:</p><ul><li>Fair locking</li><li>Try Lock</li><li>Interruptible Lock</li><li>Better flexibility</li></ul><p>I use locks only when simpler solutions are insufficient.</p><h3>24. Have you used the volatile keyword? Does volatile guarantee thread safety?</h3><p><strong>Interviewer:</strong><br>What problem does volatile solve?</p><p><strong>Candidate:</strong></p><p>volatile guarantees visibility, not thread safety.</p><p>Example:</p><pre>private volatile boolean running;</pre><p>When one thread updates the value, other threads immediately see the change.</p><p>However:It</p><pre>counter++;</pre><p>is still not thread-safe even if the counter is volatile.</p><p>Because increment involves:</p><ol><li>Read</li><li>Modify</li><li>Write</li></ol><p>multiple operations.</p><p>For atomic updates, we should use:</p><pre>AtomicInteger</pre><p>or synchronization.</p><h3>25. You join an organization in a senior role. What value will you add in the first 90 days?</h3><p><strong>Interviewer:</strong><br>Describe your 30–60–90 day plan.</p><p><strong>Candidate:</strong></p><h4>First 30 Days — Learn</h4><ul><li>Understand the business domain.</li><li>Understand architecture.</li><li>Review codebase.</li><li>Build relationships with stakeholders.</li><li>Learn deployment pipelines.</li></ul><h4>Next 30 Days — Contribute</h4><ul><li>Fix bugs.</li><li>Improve code quality.</li><li>Participate in design discussions.</li><li>Improve documentation.</li></ul><h4>Final 30 Days — Lead</h4><ul><li>Drive improvements.</li><li>Mentor team members.</li><li>Identify technical debt.</li><li>Propose scalable architecture enhancements.</li></ul><p>The objective is to deliver value while earning trust.</p><h3>26. Design a URL Shortener like Bit.ly</h3><p><strong>Interviewer:</strong><br>How would you design a URL shortening service?</p><p><strong>Candidate:</strong></p><h4>Requirements</h4><ul><li>Short URL generation</li><li>Redirection</li><li>High availability</li><li>Analytics support</li></ul><h4>APIs</h4><p>Create Short URL</p><pre>POST /shorten</pre><p>Redirect</p><pre>GET /{shortCode}</pre><h4>Database</h4><pre>id<br>original_url<br>short_code<br>created_at</pre><h4>Short Code Generation</h4><p>Options:</p><ul><li>Base62 Encoding</li><li>Random String</li><li>Distributed ID Generator</li></ul><p>Example:</p><pre>https://myapp.com/aB12Xz</pre><h4>Read Optimization</h4><p>Since redirects are read-heavy:</p><ul><li>Redis Cache</li><li>CDN</li><li>Database Replicas</li></ul><h4>High-Level Flow</h4><ol><li>User submits URL.</li><li>The system generates a short code.</li><li>Mapping stored in the database.</li><li>Code cached in Redis.</li><li>Redirect request fetches original URL.</li><li>User redirected using HTTP 301/302.</li></ol><h4>Scaling Considerations</h4><ul><li>Rate Limiting</li><li>Analytics Collection</li><li>Cache Layer</li><li>Database Sharding</li><li>Monitoring</li></ul><p>A senior-level answer should focus not only on implementation but also on scalability and reliability trade-offs.</p><h4>Final Thoughts</h4><p>These final questions assess areas that differentiate senior engineers from mid-level developers:</p><ul><li>Concurrency</li><li>Distributed Systems</li><li>Leadership</li><li>Ownership</li><li>System Design</li></ul><p>Companies increasingly evaluate not just coding ability but how engineers think about scale, reliability, and business impact.</p><p>Happy learning</p><p>Rajat Sharma</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cfde9392a2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Senior Java & Spring Boot Interview Questions Explained For Interviews — Part 2]]></title>
            <link>https://medium.com/@rajatmtr30/senior-java-spring-boot-interview-questions-explained-for-interviews-part-2-d9c4fac254ca?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9c4fac254ca</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 13:01:01 GMT</pubDate>
            <atom:updated>2026-06-03T13:01:01.385Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2: Testing, Java Fundamentals &amp; Engineering Mindset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UugvL-UXCRUoDS9JXynmA.png" /></figure><h3>11. Integration tests take one hour to run every day. How would you reduce the execution time?</h3><p><strong>Interviewer:</strong><br>Your integration test suite takes almost one hour. How would you optimize it?</p><p><strong>Candidate:</strong></p><p>The first step is identifying where the time is being spent.</p><p>My approach would be:</p><ul><li>Separate Unit Tests from Integration Tests.</li><li>Run Unit Tests on every commit.</li><li>Run Integration Tests in parallel.</li><li>Reuse containers using Testcontainers.</li><li>Avoid unnecessary Spring Context reloads.</li><li>Mock external dependencies.</li><li>Execute only impacted tests during pull requests.</li></ul><p>For example, if every integration test starts a new Spring Context, startup time becomes the bottleneck. Context reuse can significantly reduce execution time.</p><p>The goal is not simply faster execution but maintaining confidence while reducing feedback time.</p><h3>12. How do you write JUnit test cases? Which annotations do you commonly use?</h3><p><strong>Interviewer:</strong><br>Walk me through your approach to writing unit tests.</p><p><strong>Candidate:</strong></p><p>I generally follow the Arrange-Act-Assert pattern.</p><h3>Common Annotations</h3><pre>@SpringBootTest<br>@ExtendWith(MockitoExtension.class)<br>@Mock<br>@InjectMocks<br>@BeforeEach<br>@AfterEach<br>@Test</pre><p>Example:</p><pre>@Mock<br>private UserRepository repository;</pre><pre>@InjectMocks<br>private UserService service;</pre><pre>@Test<br>void shouldReturnUser() {<br>    when(repository.findById(1L))<br>        .thenReturn(Optional.of(user));</pre><pre>    User result = service.getUser(1L);</pre><pre>    assertEquals(user.getId(), result.getId());<br>}</pre><p>I focus on testing behavior rather than implementation details.</p><h3>13. Tell me about a time when you took ownership of a failing module or handled conflict within a team.</h3><p><strong>Interviewer:</strong><br>Can you share a real ownership experience?</p><p><strong>Candidate:</strong></p><p>In one project, a critical module was frequently failing in production.</p><p>Instead of treating it as somebody else’s issue, I:</p><ul><li>Investigated logs and monitoring dashboards.</li><li>Identified root causes.</li><li>Coordinated with QA and DevOps teams.</li><li>Created a stabilization plan.</li><li>Implemented fixes and monitoring.</li></ul><p>For team conflicts, I focus on understanding the technical concern rather than the individual. Most conflicts are solved when discussions become data-driven rather than opinion-driven.</p><p>Ownership means taking responsibility for outcomes, not just tasks.</p><h3>14. What’s more important: Perfect code or On-Time Delivery?</h3><p><strong>Interviewer:</strong><br>Which one would you prioritize?</p><p><strong>Candidate:</strong></p><p>Neither extreme is ideal.</p><p>Perfect code that misses business deadlines creates business problems.</p><p>Fast delivery with poor code creates technical debt.</p><p>My approach is:</p><ul><li>Deliver on time.</li><li>Maintain acceptable engineering standards.</li><li>Refactor where needed afterward.</li></ul><p>Software engineering is often about balancing trade-offs rather than optimizing a single dimension.</p><h3>15. Have you worked with @Transactional?</h3><p><strong>Interviewer:</strong><br>How have you used transactional annotations?</p><p><strong>Candidate:</strong></p><p>Yes.</p><p>@Transactional ensures that multiple database operations execute as a single unit.</p><p>Example:</p><pre>@Transactional<br>public void transferMoney() {<br>    debitAccount();<br>    creditAccount();<br>}</pre><p>If any operation fails, the entire transaction is rolled back.</p><p>Important concepts:</p><ul><li>Propagation</li><li>Isolation Levels</li><li>Rollback Rules</li><li>Read-Only Transactions</li></ul><p>Understanding transaction boundaries is critical in enterprise applications.</p><h3>16. Field Injection vs Setter Injection vs Constructor Injection</h3><p><strong>Interviewer:</strong><br>Which injection style do you prefer?</p><p><strong>Candidate:</strong></p><p>I strongly prefer Constructor Injection.</p><p>Example:</p><pre>@Service<br>public class UserService {</pre><pre>    private final UserRepository repository;</pre><pre>    public UserService(UserRepository repository) {<br>        this.repository = repository;<br>    }<br>}</pre><p>Advantages:</p><ul><li>Easier testing</li><li>Immutable dependencies</li><li>Mandatory dependencies enforced</li><li>Better design</li></ul><p>Field injection is convenient but harder to test and maintain.</p><h3>17. Why is String immutable in Java?</h3><p><strong>Interviewer:</strong><br>Why did Java make String immutable?</p><p><strong>Candidate:</strong></p><p>There are several reasons:</p><h3>Security</h3><p>Strings are used for:</p><ul><li>Database URLs</li><li>Usernames</li><li>Passwords</li><li>File Paths</li></ul><p>Immutability prevents accidental modification.</p><h3>Thread Safety</h3><p>Immutable objects are naturally thread-safe.</p><h3>String Pool Optimization</h3><p>Multiple references can safely share the same object.</p><pre>String a = &quot;hello&quot;;<br>String b = &quot;hello&quot;;</pre><p>Both may point to the same memory location.</p><h3>18. If two objects are equal according to equals(), can their hashCode() be different?</h3><p><strong>Interviewer:</strong><br>What does the Java contract say?</p><p><strong>Candidate:</strong></p><p>No.</p><p>If: a.equals(b) == true</p><p>then: a.hashCode() == b.hashCode()</p><p>must also be true.</p><p>Otherwise, collections such as:</p><ul><li>HashMap</li><li>HashSet</li><li>ConcurrentHashMap</li></ul><p>will behave incorrectly.</p><p>However, two different objects may still share the same hash code.</p><h3>19. Why can’t @Autowired be used on local variables or static fields?</h3><p><strong>Interviewer:</strong><br>Why does Spring restrict this?</p><p><strong>Candidate:</strong></p><p>Spring manages dependencies at the bean level.</p><h3>Local Variables</h3><p>Local variables exist only during method execution.</p><p>Spring cannot inject dependencies into something that does not exist during bean creation.</p><h3>Static Fields</h3><p>Static fields belong to the class rather than a bean instance.</p><p>Since Spring manages bean instances, static dependency injection is not supported reliably.</p><p>This is why constructor injection is preferred.</p><h3>20. How does Java choose between overloaded methods taking int and Integer?</h3><p><strong>Interviewer:</strong><br>Explain method selection.</p><p><strong>Candidate:</strong></p><p>Consider:</p><pre>void test(int x)<br>void test(Integer x)</pre><p>Call:</p><pre>test(10);</pre><p>Java prefers:</p><pre>test(int x)</pre><p>because it is an exact primitive match.</p><p>If:</p><pre>Integer num = 10;<br>test(num);</pre><p>then:</p><pre>test(Integer x)</pre><p>is selected.</p><p>Java follows overload resolution rules:</p><ol><li>Exact Match</li><li>Primitive Widening</li><li>Autoboxing</li><li>Varargs</li></ol><p>Understanding these rules helps avoid unexpected behavior.</p><p>Visit Part 3 for the next set of questions</p><p>Happy Learning</p><p>Rajat Sharma</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9c4fac254ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Senior Java & Spring Boot Interview Questions Explained For Interviews - Part 1]]></title>
            <link>https://medium.com/@rajatmtr30/senior-java-spring-boot-interview-questions-explained-for-interviews-part-1-939c08ab4fc3?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/939c08ab4fc3</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 06:52:41 GMT</pubDate>
            <atom:updated>2026-06-03T06:52:41.473Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1: Spring Boot Internal &amp; Backend Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UugvL-UXCRUoDS9JXynmA.png" /></figure><h3>1. What happens when you start a Spring Boot application?</h3><p><strong>Interviewer:</strong><br>What exactly happens internally when you start a Spring Boot application?</p><p><strong>Candidate:</strong></p><p>When a Spring Boot application starts, a series of initialization steps occur behind the scenes.</p><p>First, the JVM loads the application’s main class and executes the main() method. Inside this method, Spring Boot starts the application context using SpringApplication.run().</p><p>The framework then:</p><ol><li>Creates and prepares the Spring Application Context.</li><li>Reads configuration files such as application.properties or application.yml.</li><li>Scans for components using component scanning.</li><li>Processes auto-configurations.</li><li>Creates and initializes beans.</li><li>Starts the embedded server (Tomcat, Jetty, or Undertow).</li><li>Publishes startup events.</li><li>Marks the application as ready to receive requests.</li></ol><p>In short, Spring Boot automates what would otherwise require extensive XML or Java configuration.</p><p><strong>Why interviewers ask this:</strong><br>They want to know whether you understand Spring Boot beyond writing controllers and services.</p><h3>2. What role does SpringApplication.run() play?</h3><p><strong>Interviewer:</strong><br>We always write SpringApplication.run(). What exactly does it do?</p><p><strong>Candidate:</strong></p><p>SpringApplication.run() is the entry point responsible for bootstrapping the entire Spring Boot application.</p><p>Internally it:</p><ul><li>Creates the Application Context.</li><li>Loads Environment properties.</li><li>Applies auto-configurations.</li><li>Performs component scanning.</li><li>Creates beans.</li><li>Starts the embedded web server if required.</li><li>Triggers lifecycle callbacks and events.</li></ul><p>Without this method, Spring Boot would never initialize its container.</p><p>Example:</p><pre>@SpringBootApplication<br>public class Application {<br>    public static void main(String[] args) {<br>        SpringApplication.run(Application.class, args);<br>    }<br>}</pre><p>Think of it as the conductor of an orchestra coordinating every Spring component.</p><h3>3. Explain how Auto Configuration works internally.</h3><p><strong>Interviewer:</strong><br>Everyone says Spring Boot provides auto-configuration. How does it actually work?</p><p><strong>Candidate:</strong></p><p>Auto-configuration is Spring Boot’s ability to automatically configure beans based on dependencies available on the classpath.</p><p>For example:</p><p>If Spring Boot detects:</p><pre>spring-boot-starter-data-jpa</pre><p>It automatically creates:</p><ul><li>EntityManagerFactory</li><li>DataSource</li><li>TransactionManager</li></ul><p>without manual configuration.</p><p>Internally, Spring Boot uses conditional annotations such as:</p><pre>@ConditionalOnClass<br>@ConditionalOnBean<br>@ConditionalOnMissingBean<br>@ConditionalOnProperty</pre><p>These conditions determine whether a configuration should be activated.</p><p>This significantly reduces boilerplate code.</p><h3>4. How does Spring Boot decide which Auto Configurations to enable?</h3><p><strong>Interviewer:</strong><br>How does Spring Boot know which auto-configuration should be applied?</p><p><strong>Candidate:</strong></p><p>Spring Boot looks at a metadata file called:</p><pre>META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports</pre><p>This file contains a list of auto-configuration classes.</p><p>During startup:</p><ol><li>Spring reads this file.</li><li>Loads all configuration classes.</li><li>Evaluates conditional annotations.</li><li>Applies only to the configurations whose conditions match.</li></ol><p>Example:</p><pre>@ConditionalOnClass(DataSource.class)</pre><p>If the DataSource class exists on the classpath, the configuration becomes active.</p><p>This mechanism is why simply adding a dependency often enables a feature automatically.</p><h3>5. A Query returns 2 lakh rows, and the service throws OutOfMemoryError. How would you optimize it?</h3><p><strong>Interviewer:</strong><br>A query returns 200,000 records, and your service crashes with OutOfMemoryError. What would you do?</p><p><strong>Candidate:</strong></p><p>Loading 200,000 records into memory at once is rarely a good idea.</p><p>Possible solutions:</p><h4>Pagination</h4><pre>Page&lt;User&gt; users = repository.findAll(<br>    PageRequest.of(page, size)<br>);</pre><p>Fetch only the required chunk.</p><h4>Streaming</h4><pre>Stream&lt;User&gt; findAllBy();</pre><p>Process records gradually instead of loading everything.</p><h4>Batch Processing</h4><p>Process data in chunks of 1000–5000 records.</p><h4>Database Filtering</h4><p>Push filtering and aggregation to the database rather than Java memory.</p><h4>Projection</h4><p>Fetch only required columns.</p><pre>select id,name from users</pre><p>instead of entire entities.</p><p>The best optimization is usually pagination combined with projections.</p><h3>6. Explain Eager Loading and Lazy Loading.</h3><p><strong>Interviewer:</strong><br>What is the difference between eager and lazy loading?</p><p><strong>Candidate:</strong></p><h4>Eager Loading</h4><p>Associated entities are loaded immediately.</p><pre>@OneToMany(fetch = FetchType.EAGER)</pre><p>When the parent entity is fetched, related entities are also fetched.</p><h4>Lazy Loading</h4><p>Associated entities are loaded only when accessed.</p><pre>@OneToMany(fetch = FetchType.LAZY)</pre><p>Benefits:</p><ul><li>Lower memory consumption</li><li>Faster initial query execution</li></ul><p>However, lazy loading may introduce additional queries if not handled carefully.</p><h3>7. How does Lazy Loading contribute to the N+1 problem?</h3><p><strong>Interviewer:</strong><br>Can Lazy Loading create performance issues?</p><p><strong>Candidate:</strong></p><p>Yes.</p><p>Consider fetching 100 Orders.</p><p>First query:</p><pre>SELECT * FROM orders;</pre><p>Then for each order:</p><pre>SELECT * FROM items WHERE order_id = ?;</pre><p>Total queries:</p><pre>1 + 100 = 101 queries</pre><p>This is known as the N+1 Query Problem.</p><p>Solutions:</p><ul><li>JOIN FETCH</li><li>Entity Graphs</li><li>Batch Fetching</li><li>DTO Projections</li></ul><p>A senior engineer should always watch query counts, not just response times.</p><h3>8. One downstream service becomes slow. How do you prevent your service from degrading?</h3><p><strong>Interviewer:</strong><br>Suppose Service A calls Service B. Service B becomes slow. How would you protect Service A?</p><p><strong>Candidate:</strong></p><p>I would implement the Resilience Pattern using libraries such as Resilience4j.</p><p>Key techniques:</p><h4>Timeout</h4><p>Fail fast when a dependency is slow.</p><h4>Circuit Breaker</h4><p>Stop calling a failing service temporarily.</p><h4>Retry</h4><p>Retry transient failures.</p><h4>Bulkhead</h4><p>Prevent one dependency from consuming all resources.</p><h4>Fallback</h4><p>Provide an alternative response.</p><p>Example:</p><pre>@CircuitBreaker(name=&quot;paymentService&quot;)</pre><p>This prevents cascading failures across microservices.</p><h3>9. What are some real features built into Spring Security?</h3><p><strong>Interviewer:</strong><br>What functionality does Spring Security provide out of the box?</p><p><strong>Candidate:</strong></p><p>Spring Security provides:</p><ul><li>Authentication</li><li>Authorization</li><li>Session Management</li><li>CSRF Protection</li><li>Password Encryption</li><li>OAuth2 Integration</li><li>JWT Support</li><li>Method-Level Security</li><li>Security Headers</li><li>Protection against common attacks</li></ul><p>Example:</p><pre>@PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)</pre><p>This restricts access based on roles.</p><p>Spring Security acts as the security gatekeeper of the application.</p><h3>10. ResponseEntity vs Plain Object Response</h3><p><strong>Interviewer:</strong><br>One API returns a ResponseEntity, and another returns a plain object. What’s the difference?</p><p><strong>Candidate:</strong></p><p>Returning a plain object:</p><pre>@GetMapping<br>public User getUser() {<br>    return user;<br>}</pre><p>Spring automatically returns HTTP 200.</p><p>Returning ResponseEntity:</p><pre>@GetMapping<br>public ResponseEntity&lt;User&gt; getUser() {<br>    return ResponseEntity.ok(user);<br>}</pre><p>Benefits:</p><ul><li>Control HTTP status code</li><li>Control headers</li><li>Return different responses based on conditions</li></ul><p>Example:</p><pre>return ResponseEntity.notFound().build();</pre><p>For enterprise APIs, ResponseEntity is generally preferred because it provides full control over the HTTP response.</p><h4>Final Thoughts</h4><p>These first ten questions focus on Spring Boot internals, performance optimization, microservices resilience, and API design. Senior-level interviews increasingly emphasize understanding what happens behind the framework rather than simply using annotations.</p><p>In Part 2, we’ll cover testing strategies, Java fundamentals, dependency injection, transactions, immutability, and engineering decision-making.</p><p>Happy Learning</p><p>Rajat Sharma</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=939c08ab4fc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java, JRE, JVM — Complete Interview Guide with Real Interview Questions, Architecture, Memory Model…]]></title>
            <link>https://medium.com/@rajatmtr30/java-jre-jvm-complete-interview-guide-with-real-interview-questions-architecture-memory-model-995cdb2b525a?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/995cdb2b525a</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 10:12:28 GMT</pubDate>
            <atom:updated>2026-04-28T10:12:28.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java, JRE, JVM — Complete Interview Guide with Real Interview Questions, Architecture, Memory Model &amp; Performance Tuning</h3><p>This guide now includes the <strong>exact way interviewers commonly ask JVM questions</strong> in real interviews (service-based + product companies + senior backend roles).</p><p>Example interview styles:</p><ul><li>Direct definition questions</li><li>Scenario-based production questions</li><li>Deep-dive architecture questions</li><li>Follow-up trap questions</li></ul><h4>How Interviewers Usually Ask JVM Questions</h4><h4>Basic Level</h4><ul><li>What is a JVM?</li><li>What is the difference between JVM, JDK, and JRE?</li><li>Why is the Java platform independent?</li><li>What happens when we run a Java program?</li></ul><h4>Intermediate Level</h4><ul><li>Explain JVM architecture.</li><li>What are the runtime memory areas in the JVM?</li><li>Difference between a heap and a stack?</li><li>What is class loading in Java?</li><li>What is Metaspace?</li></ul><h4>Multithreading/JMM Questions</h4><ul><li>What is the Java Memory Model?</li><li>Explain the happens-before relationship.</li><li>How does volatile work internally?</li><li>Why is volatile not atomic?</li><li>Difference between synchronized, volatile, and atomic classes?</li></ul><h4>Senior/Production Questions</h4><ul><li>Your application is facing frequent full GCs. How will you troubleshoot?</li><li>Your microservice latency suddenly increased after deployment. How would you debug JVM issues?</li><li>How do you analyse heap dumps?</li><li>How do you tune JVM for high-traffic systems?</li><li>How do you optimize memory in containerized Java applications?</li></ul><p>This article covers commonly asked <strong>Java/JVM interview questions</strong> in a structured way with explanations, examples, diagrams, and production troubleshooting scenarios.</p><h4>1) “What is JVM? What is the difference between JVM, JRE and JDK?”</h4><h4>JVM (Java Virtual Machine)</h4><p>JVM is an engine that executes Java bytecode and converts it into machine-level instructions.</p><pre>.java file → javac compiler → .class bytecode → JVM → OS Machine Code</pre><h4>Responsibilities of JVM:</h4><ul><li>Loads class files</li><li>Verifies bytecode</li><li>Allocates memory</li><li>Executes code</li><li>Performs garbage collection</li><li>Provides platform independence</li></ul><h4>Why is the Java platform independent?</h4><p>Because Java code runs on the JVM instead of directly running on the OS.</p><p>Example:</p><ul><li>Compile on Windows</li><li>Run same .class file on Linux/Mac if JVM exists</li></ul><h4>JRE (Java Runtime Environment)</h4><p>JRE provides an environment to run Java applications.</p><p>It contains:</p><ul><li>JVM and Core libraries</li><li>Supporting files</li></ul><p>Used by:<br>People who only want to run Java apps.</p><h4>JDK (Java Development Kit)</h4><p>JDK is used to develop Java applications.</p><p>It contains:</p><ul><li>JRE</li><li>JVM</li><li>Development tools:</li><li>javac</li><li>javadoc</li><li>jdb</li><li>jar</li></ul><pre>JDK<br> ├── JRE<br> │    ├── JVM<br> │    ├── Java Libraries<br> │<br> ├── Compiler Tools<br> ├── Debug Tools</pre><h4>2) “Can you explain JVM architecture and its major components?”</h4><p>JVM architecture mainly consists of:</p><ol><li>Class Loader</li><li>Runtime Data Areas</li><li>Execution Engine</li><li>Native Interface</li></ol><h4>JVM Architecture Diagram</h4><pre>Class Loader<br>             ↓<br>   Runtime Data Areas<br>             ↓<br>      Execution Engine<br>             ↓<br>      Native Libraries</pre><h4>A. Class Loader</h4><p>Loads .class files into memory.</p><h4>Phases:</h4><h4>1. Loading</h4><p>Loads class bytecode.</p><h4>2. Linking</h4><ul><li>Verification</li><li>Preparation</li><li>Resolution</li></ul><h4>3. Initialization</h4><p>Initializes static variables.</p><p>Example:</p><pre>class Test {<br>   static int x = 10;<br>}</pre><p>During initialization x=10 gets assigned.</p><h4>B. Runtime Data Areas</h4><h4>Heap</h4><p>Stores:</p><ul><li>Objects</li><li>Instance variables</li></ul><p>Shared among threads.</p><p>Example:</p><pre>new Employee();</pre><p>Stored in the heap.</p><h4>Stack</h4><p>Stores:</p><ul><li>Method calls</li><li>Local variables</li></ul><p>Thread specific.</p><p>Example:</p><pre>void test(){<br>   int x = 10;<br>}</pre><p>x stored in stack.</p><h4>Metaspace</h4><p>Stores:</p><ul><li>Class metadata</li><li>Method metadata</li></ul><p>Introduced in Java 8.</p><h4>Code Cache</h4><p>Stores JIT-compiled native code.</p><p>Frequently executed code gets stored here.</p><h4>PC Register</h4><p>Stores current instruction for each thread.</p><h4>Native Method Stack</h4><p>Stores execution info for native methods.</p><p>Example:</p><pre>System.arraycopy()</pre><h4>3) “What are thread-specific memory areas in the JVM, and what happens when too many threads are created?”</h4><p>Each thread gets:</p><ul><li>Java Stack</li><li>PC Register</li><li>Native Method Stack</li></ul><h4>Why important?</h4><p>When too many threads are created:</p><ul><li>More stack memory consumed</li><li>Context switching increases</li><li>CPU overhead increases</li><li>Can lead to:</li></ul><pre>OutOfMemoryError: unable to create native thread</pre><h4>Example</h4><p>Suppose:</p><p>Each thread stack size = 1MB</p><p>1000 threads:</p><pre>1000 × 1MB = 1GB memory usage</pre><p>This becomes dangerous in microservices.</p><h4>Solution</h4><p>Use thread pools:</p><pre>ExecutorService service = Executors.newFixedThreadPool(10);</pre><h4>4) “What is Java Memory Model and why do we need it?”</h4><p>JMM defines how threads interact through memory.</p><p>It guarantees:</p><ul><li>Visibility</li><li>Atomicity</li><li>Ordering</li></ul><h4>Problem without JMM</h4><p>Thread A updates the variable.<br>Thread B may not immediately see the updated value.</p><p>Because CPU cache may contain stale data.</p><h4>Example</h4><pre>boolean flag = false;</pre><pre>Thread A:<br>flag = true;</pre><pre>Thread B:<br>while(!flag){ }</pre><p>Thread B may loop forever without proper visibility.</p><h4>5) “What is the happens-before relationship in the Java Memory Model?”</h4><p>Defines execution ordering guarantees. If A happens-before B:</p><p>Then changes in A are visible to B.</p><h4>Rules</h4><h4>1. Program Order Rule</h4><pre>x=1;<br>y=2;</pre><p>x happens before y.</p><h4>2. Lock Rule</h4><p>Unlock happens-before next lock.</p><h4>3. Volatile Rule</h4><p>Write happens-before read.</p><h4>4. Thread Start Rule</h4><pre>thread.start()</pre><p>Happens before thread execution.</p><h4>5. Thread Join Rule</h4><pre>thread.join()</pre><p>Ensures completion visibility.</p><h4>6) “How does volatile work internally, and how are atomic operations handled in Java?”</h4><h4>Volatile</h4><p>Ensures:</p><ul><li>Visibility</li><li>Ordering</li></ul><p>Does NOT guarantee atomicity.</p><p>Example:</p><pre>volatile boolean running = true;</pre><p>Used for flags.</p><h4>Why is volatile not atomic?</h4><pre>count++</pre><p>Actually:</p><ol><li>Read</li><li>Increment</li><li>Write</li></ol><p>Multiple threads may conflict.</p><h4>Atomic Operations</h4><p>Use:</p><pre>AtomicInteger</pre><p>Example:</p><pre>AtomicInteger count = new AtomicInteger();<br>count.incrementAndGet();</pre><p>Uses CAS (Compare and Swap).</p><h4>7) “Your production service shows response time spikes and GC logs show frequent Full GCs. How would you troubleshoot it?”</h4><h4>Problem</h4><p>Microservice response time spikes. GC logs show frequent Full GC.</p><h4>Step 1: Analyze Heap</h4><p>Use:</p><ul><li>JVisualVM</li><li>Eclipse MAT</li><li>Heap dump</li></ul><p>Check:</p><ul><li>Memory leaks</li><li>Large collections</li><li>Cache growth</li></ul><h4>Step 2: Analyze GC logs</h4><p>Enable:</p><pre>-Xlog:gc*</pre><p>Check:</p><ul><li>Full GC frequency</li><li>Pause times</li><li>Heap occupancy</li></ul><p>Example:</p><pre>Full GC (Allocation Failure)</pre><p>Indicates heap pressure.</p><h4>Step 3: Check JFR</h4><p>Java Flight Recorder helps analyze:</p><ul><li>CPU usage</li><li>Lock contention</li><li>Allocation hotspots</li><li>Thread blocking</li></ul><pre>-XX:StartFlightRecording</pre><h4>Step 4: Check JIT logs</h4><pre>-XX:+PrintCompilation</pre><p>Check:</p><ul><li>Deoptimization</li><li>Compilation delays</li></ul><h4>Root Causes</h4><h4>Memory leak</h4><p>Objects are retained forever.</p><h4>Huge object creation</h4><p>Too many temporary objects.</p><p>Example:</p><pre>for(int i=0;i&lt;1000000;i++){<br>   new String(&quot;abc&quot;);<br>}</pre><h4>Incorrect heap sizing</h4><p>Too small heap causes frequent GC.</p><h4>Too many threads</h4><p>Consumes memory.</p><h4>Solutions</h4><ul><li>Fix memory leaks</li><li>Use proper cache eviction</li><li>Increase heap</li><li>Reduce object creation</li><li>Tune GC algorithm</li></ul><h4>8) “What JVM arguments have you used in production to tune performance?”</h4><h4>Heap settings</h4><pre>-Xms2g<br>-Xmx4g</pre><ul><li>Xms → initial heap</li><li>Xmx → max heap</li></ul><h4>Stack size</h4><pre>-Xss512k</pre><p>Controls per-thread stack.</p><h4>GC selection</h4><h4>G1 GC</h4><pre>-XX:+UseG1GC</pre><p>Best for most services.</p><h4>ZGC</h4><pre>-XX:+UseZGC</pre><p>Very low latency.</p><h4>GC logs</h4><pre>-Xlog:gc*</pre><h4>Heap dump on OOM</h4><pre>-XX:+HeapDumpOnOutOfMemoryError</pre><h4>Metaspace limits</h4><pre>-XX:MetaspaceSize=256m<br>-XX:MaxMetaspaceSize=512m</pre><h4>String Deduplication</h4><pre>-XX:+UseStringDeduplication</pre><p>Useful when many duplicate strings exist.</p><h4>9) “What is Metaspace and how is it different from PermGen?”</h4><h4>PermGen (Before Java 8)</h4><p>Stored:</p><ul><li>Class metadata</li><li>String pool</li><li>Static variables</li></ul><p>Problem:</p><p>Fixed size → frequent:</p><pre>OutOfMemoryError: PermGen space</pre><h4>Metaspace (Java 8+)</h4><p>Replaced PermGen.</p><p>Stores:</p><ul><li>Class metadata</li></ul><p>Stored in native memory.</p><p>Grows dynamically.</p><h4>Real Interview Tip</h4><p>When answering JVM questions:</p><ol><li>Start with the definition</li><li>Explain architecture</li><li>Give example</li><li>Mention production use case</li></ol><p>This makes your answer stand out in senior Java interviews.</p><p>For your <strong>6 years of Java + microservices background</strong>, focus heavily on:</p><ul><li>GC tuning</li><li>Memory leaks</li><li>Thread pools</li><li>JVM monitoring</li><li>Production debugging</li></ul><p>These are frequently asked in backend interviews at product companies.</p><p>Happy Learning</p><p>Rajat Sharma</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=995cdb2b525a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context-Driven Development: A Practical Way to Make Changes Without Breaking Your System]]></title>
            <link>https://medium.com/@rajatmtr30/context-driven-development-a-practical-way-to-make-changes-without-breaking-your-system-8935867071c8?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8935867071c8</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[adoption]]></category>
            <category><![CDATA[cursor]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 04:31:03 GMT</pubDate>
            <atom:updated>2026-04-08T04:31:03.077Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications are complex. A small change in one feature can unexpectedly impact multiple modules, APIs, or user journeys. Because of this, making safe and predictable updates requires more than just coding skills — it requires <strong>clarity of context</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwwiifDfG6O4FrFzHjEWGQ.png" /></figure><p>In this article, I’ll explain a simple and practical approach to implementing changes using a <strong>context-driven development method</strong>, ensuring updates stay limited to the intended flow and do not affect other parts of the platform.</p><h3>Why Context Matters in Software Changes</h3><p>Many development teams face similar problems:</p><ul><li>A small change breaks an unrelated feature</li><li>AI tools struggle to understand the codebase structure</li><li>Developers spend time figuring out how APIs connect</li><li>Feature flows are not clearly documented</li><li>Changes impact multiple services unintentionally</li></ul><p>To avoid this, we need a structured way to define how the system works before making modifications.</p><p>This is where <strong>context-driven development</strong> becomes useful.</p><h3>Step 1 — Limit the Scope of Change</h3><p>The first step is identifying exactly <strong>which flow needs modification</strong>.</p><p>For example, if a change is required in a signing flow, we ensure the update affects only that flow and <strong>does not impact other parts of the application</strong>.</p><p>This prevents side effects and keeps the rest of the system stable.</p><p>Instead of changing multiple components blindly, we focus only on:</p><ul><li>The specific feature</li><li>The related APIs</li><li>The relevant business logic</li><li>The impacted user journey</li></ul><h3>Step 2 — Create a Structured Context</h3><p>Before making any changes, we create a <strong>project context</strong> describing how the system works.</p><p>This context acts as a shared understanding between developers and AI tools.</p><p>Typical context includes:</p><h3>API Understanding</h3><ul><li>API endpoints</li><li>Request format</li><li>Response structure</li><li>Authentication requirements</li></ul><h3>System Behaviour</h3><ul><li>How services communicate</li><li>Dependencies between modules</li><li>Business rules and validations</li></ul><h3>Integration Points</h3><ul><li>External services</li><li>Database interactions</li><li>Event triggers</li></ul><p>This structured information makes it easier to understand where changes should happen.</p><h3>Step 3 — Understand the Current Flow</h3><p>Before modifying anything, we clearly define the <strong>existing flow</strong>.</p><p>This helps ensure we do not accidentally break current functionality.</p><p>Typical flow understanding includes:</p><ul><li>What happens before login</li><li>What happens after login</li><li>How the user interacts with the feature</li><li>Which APIs are triggered</li><li>Where validations occur</li><li>Where conditions or decision points exist</li></ul><p>Once the current flow is documented, we get a clear picture of how the feature behaves today.</p><h3>Step 4 — Define the Required Change</h3><p>After understanding the current behaviour, we describe the expected behaviour after the change.</p><p>At this stage we:</p><ul><li>Explain what should change</li><li>Identify impacted APIs</li><li>Define updates in business logic</li><li>Check whether existing validations need modification</li><li>Ensure other modules remain unaffected</li></ul><p>This step ensures that the change is intentional and controlled.</p><h3>Step 5 — Implement Changes Safely</h3><p>With a clear understanding of context and flow, implementation becomes much easier.</p><p>Benefits include:</p><ul><li>Reduced risk of breaking existing features</li><li>Faster development cycles</li><li>Better collaboration between developers</li><li>AI tools can understand the project more accurately</li><li>Easier debugging and maintenance</li></ul><p>Because the system context is already defined, updates remain predictable.</p><h3>Why This Approach Works Well with AI Tools</h3><p>AI tools perform better when they understand the system structure.</p><p>Providing context such as:</p><ul><li>API definitions</li><li>Flow descriptions</li><li>dependencies</li><li>expected behaviour</li></ul><p>helps AI generate more accurate solutions for:</p><ul><li>feature implementation</li><li>bug fixes</li><li>refactoring suggestions</li><li>architecture improvements</li></ul><p>Instead of guessing how the system works, the AI already has a clear understanding of the project.</p><h3>Key Takeaways</h3><p>A structured context makes development more reliable and scalable.</p><h3>The approach can be summarized as:</h3><ol><li>Identify the exact flow that needs modification</li><li>Create structured context including APIs and system behaviour</li><li>Understand the existing flow clearly</li><li>Define the required change precisely</li><li>Implement updates without affecting other modules</li></ol><p>By following this process, teams can ensure that changes remain <strong>controlled, predictable, and easy to maintain</strong>.</p><p>If you’re working on complex applications or using AI-assisted development tools, adopting a context-driven approach can significantly improve both <strong>development speed</strong> and <strong>code quality</strong>.</p><p>Happy Learning</p><p>Rajat Sharma</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8935867071c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Teach AI Assistants Our Microservices Platform (Without Letting Them Hallucinate)]]></title>
            <link>https://medium.com/@rajatmtr30/how-we-teach-ai-assistants-our-microservices-platform-without-letting-them-hallucinate-f60d8595e519?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/f60d8595e519</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 06:21:42 GMT</pubDate>
            <atom:updated>2026-04-07T06:21:42.156Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern software systems are no longer simple monoliths. They are distributed, event-driven, and often span dozens of microservices. While this architecture improves scalability and flexibility, it creates a new problem:</p><blockquote><strong><em>Understanding the system becomes harder than building the system.</em></strong></blockquote><p>For engineers, onboarding into a large microservice ecosystem requires reading scattered documentation, reverse-engineering flows, and connecting the dots between APIs, events, and databases.</p><p>For AI tools, the problem is even bigger.</p><p>Generic AI assistants often:</p><ul><li>Confuse service boundaries</li><li>Assume APIs that don’t exist</li><li>Miss asynchronous event flows</li><li>Provide solutions that break existing architecture</li></ul><p>To solve this, we started treating <strong>context as a first-class engineering artifact</strong>.</p><p>We built a structured <strong>AI context repository</strong> that helps both humans and AI systems understand our platform consistently and accurately.</p><h3>The Problem: AI Without Context Is Guessing</h3><p>Large language models are powerful, but they do not automatically understand your architecture.</p><p>Without structured context:</p><ul><li>AI suggests endpoints that don’t exist</li><li>Async messaging flows are ignored</li><li>Data ownership boundaries get blurred</li><li>Feature designs break existing contracts</li></ul><p>In microservices, <strong>small misunderstandings create large production risks</strong>.</p><p>We needed a way to ensure that AI tools start with the same knowledge base as engineers.</p><h3>The Solution: A Structured AI Context Pack</h3><p>Instead of relying on random prompts or scattered wiki pages, we created a version-controlled <strong>AI context directory</strong> that lives alongside our codebase.</p><p>Think of it as:</p><blockquote><em>A system knowledge layer that both developers and AI assistants can rely on.</em></blockquote><p>The structure mirrors how engineers actually design features.</p><h3>Core sections of the context repository</h3><h3>1. Platform Overview</h3><p>Defines:</p><ul><li>What the system does</li><li>High-level architecture</li><li>Key design principles</li><li>Source-of-truth rules</li></ul><p>Example rule:</p><blockquote><em>If documentation conflicts with source code, source code is considered the truth.</em></blockquote><p>This prevents AI from trusting outdated documents.</p><h3>2. Service Deep Dive</h3><p>Each microservice has its own structured folder describing:</p><ul><li>Functional responsibility</li><li>API endpoints</li><li>Event producers and consumers</li><li>Database schema relationships</li><li>Internal dependencies</li></ul><p>This helps AI understand:</p><blockquote><em>Which service owns what logic.</em></blockquote><p>Instead of hallucinating connections, the AI reads actual service boundaries.</p><h3>3. Cross-Cutting Concerns</h3><p>Some components affect multiple services:</p><ul><li>authentication flows</li><li>messaging systems</li><li>shared data models</li><li>configuration patterns</li><li>retry mechanisms</li><li>external integrations</li></ul><p>These are documented separately to avoid duplication and confusion.</p><p>This ensures consistency when designing features that span multiple services.</p><h3>4. Integration Context Packs</h3><p>External providers (such as communication platforms) introduce complexity.</p><p>Instead of mixing integration details into core service documentation, we isolate them into separate context packs.</p><p>These include:</p><ul><li>channel-specific flows</li><li>error handling patterns</li><li>retry logic</li><li>webhook mapping</li><li>rate limit considerations</li></ul><p>This prevents feature design from mixing internal architecture with vendor-specific logic.</p><h3>5. Change Impact Awareness</h3><p>One of the biggest risks in microservices is unintended side effects.</p><p>The context repository includes checklists for:</p><ul><li>schema updates</li><li>new event topics</li><li>API contract changes</li><li>configuration updates</li><li>backward compatibility concerns</li></ul><p>This allows AI-assisted design to consider system-wide impact before implementation begins.</p><h3>How Engineers Use It for Feature Design</h3><p>Our feature design workflow follows a structured reading order.</p><h3>Step 1: Identify impacted services</h3><p>Engineers first locate relevant service context folders.</p><p>This clarifies:</p><ul><li>ownership boundaries</li><li>existing flows</li><li>extension points</li></ul><h3>Step 2: Validate data and contracts</h3><p>Before designing new endpoints or events, shared models and messaging definitions are reviewed.</p><p>This prevents:</p><ul><li>duplicate entities</li><li>incompatible payloads</li><li>conflicting topic naming conventions</li></ul><h3>Step 3: Check cross-cutting capabilities</h3><p>Features often involve:</p><ul><li>notifications</li><li>authentication</li><li>orchestration logic</li><li>background processing</li></ul><p>Instead of reinventing patterns, engineers reuse documented approaches.</p><h3>Step 4: Create feature workspace artifacts</h3><p>Feature-specific design artifacts are stored separately from the reference context.</p><p>This ensures:</p><ul><li>The context repository remains clean</li><li>Temporary experiments don’t pollute system documentation</li><li>AI continues to rely on validated knowledge</li></ul><h3>AI Integration: Teaching Assistants Where to Look</h3><p>We added lightweight rules that guide AI tools on how to read the repository.</p><p>Instead of loading everything into a single prompt, the AI retrieves information based on task relevance.</p><p>Example mapping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*_Z10nusYUOGUgPtg4dAXdg.png" /></figure><p>This significantly improves AI response quality while reducing hallucination risk.</p><h3>Principles That Keep Context Useful</h3><p>Maintaining an AI-ready context repository requires discipline.</p><h3>1. Code is always the source of truth</h3><p>Documentation must reflect actual implementation.</p><p>When discrepancies appear, documentation is updated.</p><h3>2. Avoid fictional architecture</h3><p>If a flow is unclear, we mark it as unknown instead of guessing.</p><p>Incorrect documentation causes more damage than missing documentation.</p><h3>3. Separate stable knowledge from temporary work</h3><p>Reference architecture evolves slowly.</p><p>Feature-specific design evolves rapidly.</p><p>Keeping them separate prevents confusion.</p><h3>Results We Observed</h3><p>After implementing structured context:</p><h3>Faster feature design</h3><p>Engineers spend less time rediscovering system behavior.</p><h3>Reduced architectural mistakes</h3><p>AI suggestions align better with existing flows.</p><h3>Improved onboarding speed</h3><p>New developers understand the system structure faster.</p><h3>More reliable AI assistance</h3><p>AI stops guessing and starts reasoning from actual architecture.</p><h3>Key Takeaway</h3><p>AI is only as good as the context it receives.</p><p>Generic prompts produce generic answers.</p><p>Structured engineering context produces architecture-aware solutions.</p><p>If you want AI to assist in real-world feature development:</p><blockquote><em>Treat system knowledge as a product.</em></blockquote><p>Create a structured context.<br>Maintain it.<br>Guide AI on how to use it.</p><p>The results compound over time.</p><p>Happy Learning</p><p>Rajat Sharma</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f60d8595e519" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behavioral Patterns in Java — Explained Simply (With Real-World Examples)]]></title>
            <link>https://medium.com/@rajatmtr30/behavioral-patterns-in-java-explained-simply-with-real-world-examples-9824ac2fc1a9?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/9824ac2fc1a9</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 09:31:00 GMT</pubDate>
            <atom:updated>2026-02-24T09:31:00.798Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Creational patterns control </em><strong><em>how objects are created</em></strong><em>.<br>Structural patterns control </em><strong><em>how objects are connected</em></strong><em>.<br>Behavioral patterns control </em><strong><em>how objects communicate and behave</em></strong><em>.</em></blockquote><p>And this is where real production systems become interesting.</p><p>In microservices, most complexity comes from:</p><ul><li>Dynamic behavior</li><li>Event-driven flows</li><li>Request processing chains</li><li>Workflow orchestration</li></ul><p>In this article, we’ll break down five essential behavioral patterns in a simple and practical way:</p><ul><li>Strategy (Payment example)</li><li>Observer (Event-driven systems)</li><li>Chain of Responsibility (Spring Filters)</li><li>Template Method</li><li>Command Pattern</li></ul><h3>1️⃣ Strategy Pattern</h3><p><strong>Change behavior without changing the class</strong></p><h3>Real-World Problem</h3><p>You’re building a payment system.</p><p>Bad design:</p><pre>public class PaymentService {<br>public void pay(String type, double amount) {<br>        if(type.equals(&quot;UPI&quot;)) {<br>            // UPI logic<br>        } else if(type.equals(&quot;CARD&quot;)) {<br>            // Card logic<br>        } else if(type.equals(&quot;NET_BANKING&quot;)) {<br>            // Net banking logic<br>        }<br>    }<br>}</pre><p>Problems:</p><ul><li>Violates Open/Closed Principle</li><li>Hard to test</li><li>Grows messy quickly</li></ul><h3>Refactored Using Strategy</h3><h3>Step 1: Define Strategy Interface</h3><pre>public interface PaymentStrategy {<br>    void pay(double amount);<br>}</pre><h3>Step 2: Implement Strategies</h3><pre>public class UpiPayment implements PaymentStrategy {<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid using UPI&quot;);<br>    }<br>}</pre><pre>public class CardPayment implements PaymentStrategy {<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid using Card&quot;);<br>    }<br>}</pre><h3>Step 3: Use Strategy</h3><pre>public class PaymentService {<br>private PaymentStrategy strategy;<br>    public PaymentService(PaymentStrategy strategy) {<br>        this.strategy = strategy;<br>    }<br>    public void process(double amount) {<br>        strategy.pay(amount);<br>    }<br>}</pre><p>Now:</p><ul><li>New payment methods = new class</li><li>No modification to existing logic</li></ul><h3>Spring Boot Version</h3><p>You can inject strategies as beans:</p><pre>@Autowired<br>private Map&lt;String, PaymentStrategy&gt; strategies;</pre><p>Now behavior becomes dynamic.</p><h3>Where It’s Used in Real Systems</h3><ul><li>Payment types</li><li>Authentication methods</li><li>Discount calculation</li><li>Tax calculation</li><li>File processing formats</li></ul><h3>2️⃣ Observer Pattern</h3><p><strong>React to events automatically</strong></p><h3>Real-World Problem</h3><p>After order placement, you need to:</p><ul><li>Send email</li><li>Update inventory</li><li>Generate invoice</li><li>Trigger analytics</li></ul><p>Bad approach:</p><pre>orderService.placeOrder();<br>emailService.send();<br>inventoryService.update();<br>analyticsService.track();</pre><p>Tightly coupled. Hard to scale.</p><h3>Observer Concept</h3><p>One object (Publisher) notifies multiple observers automatically.</p><h3>Simple Example</h3><h3>Event</h3><pre>public class OrderPlacedEvent {<br>    private String orderId;</pre><pre>    public OrderPlacedEvent(String orderId) {<br>        this.orderId = orderId;<br>    }</pre><pre>    public String getOrderId() {<br>        return orderId;<br>    }<br>}</pre><h3>Listener</h3><pre>@Component<br>public class EmailListener {<br>@EventListener<br>    public void handleOrder(OrderPlacedEvent event) {<br>        System.out.println(&quot;Sending email for order &quot; + event.getOrderId());<br>    }<br>}</pre><h3>Publisher</h3><pre>@Autowired<br>private ApplicationEventPublisher publisher;<br>public void placeOrder(String orderId) {<br>    publisher.publishEvent(new OrderPlacedEvent(orderId));<br>}</pre><p>Now:</p><ul><li>The order service doesn’t know about email.</li><li>Clean separation.</li><li>Easily extensible.</li></ul><h3>Real Microservice Use Cases</h3><ul><li>Kafka event consumers</li><li>Audit logging</li><li>Notification system</li><li>Domain events</li><li>Webhooks</li></ul><p>This pattern powers event-driven architecture.</p><h3>3️⃣ Chain of Responsibility</h3><p><strong>Process request through multiple handlers</strong></p><h3>Real-World Problem</h3><p>HTTP request must go through:</p><ul><li>Authentication</li><li>Logging</li><li>Validation</li><li>Rate limiting</li></ul><p>Instead of one giant method, we use a chain.</p><h3>Concept</h3><p>Each handler:</p><ul><li>Processes request</li><li>Passes to next handler</li></ul><h3>Simplified Example</h3><pre>public abstract class Handler {<br>protected Handler next;<br>    public void setNext(Handler next) {<br>        this.next = next;<br>    }<br>    public void handle(String request) {<br>        if(next != null) {<br>            next.handle(request);<br>        }<br>    }<br>}</pre><p>Concrete handler:</p><pre>public class AuthHandler extends Handler {<br>public void handle(String request) {<br>        System.out.println(&quot;Authenticating...&quot;);<br>        super.handle(request);<br>    }<br>}</pre><h3>Spring Example</h3><p>Spring Security filter chain:</p><ul><li>UsernamePasswordAuthenticationFilter</li><li>BasicAuthenticationFilter</li><li>ExceptionTranslationFilter</li></ul><p>Each filter passes request to next filter.</p><p>This is textbook Chain of Responsibility.</p><h3>Real Microservice Use Case</h3><ul><li>Middleware pipeline</li><li>Request validation layers</li><li>Interceptor chains</li><li>API gateway filters</li></ul><h3>4️⃣ Template Method Pattern</h3><p><strong>Define skeleton, allow customization</strong></p><h3>Real-World Problem</h3><p>Processing payments always includes:</p><ol><li>Validate</li><li>Deduct amount</li><li>Send confirmation</li></ol><p>But validation logic differs by type.</p><h3>Implementation</h3><pre>public abstract class PaymentProcessor {<br>public final void process(double amount) {<br>        validate(amount);<br>        deduct(amount);<br>        sendConfirmation();<br>    }<br>    protected abstract void validate(double amount);<br>    private void deduct(double amount) {<br>        System.out.println(&quot;Deducting amount&quot;);<br>    }<br>    private void sendConfirmation() {<br>        System.out.println(&quot;Sending confirmation&quot;);<br>    }<br>}</pre><p>Concrete class:</p><pre>public class UpiProcessor extends PaymentProcessor {<br>protected void validate(double amount) {<br>        System.out.println(&quot;Validating UPI payment&quot;);<br>    }<br>}</pre><p>Now:</p><ul><li>The algorithm structure is fixed.</li><li>Certain steps are customizable.</li></ul><h3>How Spring Uses It</h3><p>JdbcTemplate, RestTemplate Follow the template pattern.</p><p>You define:</p><ul><li>Query</li><li>RowMapper</li></ul><p>Spring handles:</p><ul><li>Connection</li><li>Exception</li><li>Resource closing</li></ul><p>This is powerful and widely used.</p><h3>5️⃣ Command Pattern</h3><p><strong>Encapsulate the request as an object</strong></p><h3>Real-World Problem</h3><p>You want:</p><ul><li>Undo/Redo functionality</li><li>Task scheduling</li><li>Background job execution</li></ul><h3>Concept</h3><p>Command wraps action into an object.</p><h3>Example</h3><p>Command interface:</p><pre>public interface Command {<br>    void execute();<br>}</pre><p>Concrete command:</p><pre>public class SendEmailCommand implements Command {<br>private EmailService emailService;<br>    public SendEmailCommand(EmailService emailService) {<br>        this.emailService = emailService;<br>    }<br>    public void execute() {<br>        emailService.sendEmail();<br>    }<br>}</pre><p>Invoker:</p><pre>public class CommandInvoker {<br>public void run(Command command) {<br>        command.execute();<br>    }<br>}</pre><h3>Real Microservice Use Case</h3><ul><li>Job queue (RabbitMQ, Kafka)</li><li>Async processing</li><li>Workflow engine</li><li>Retry mechanisms</li></ul><p>Spring Batch internally uses command-like execution models.</p><h3>Final Thoughts</h3><p>Behavioral patterns help you:</p><ul><li>Remove massive if-else blocks</li><li>Decouple services</li><li>Build event-driven systems</li><li>Structure workflows cleanly</li><li>Improve scalability</li></ul><p>In modern Spring Boot microservices, you are already using:</p><ul><li>Strategy (Security, Payment types)</li><li>Observer (Events, Kafka)</li><li>Chain (Filters)</li><li>Template (JdbcTemplate)</li><li>Command (Async tasks)</li></ul><p>What is the difference between mid-level and senior engineers?</p><p>Seniors <strong>recognize patterns consciously</strong> and use them intentionally.</p><p>In the next article, we’ll explore how these patterns combine in real microservice architectures.</p><p>Because real systems never use just one pattern — they compose many together.</p><p>Happy Learning</p><p>Rajat Sharma</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9824ac2fc1a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structural Patterns in Java (Practical Use Cases)]]></title>
            <link>https://medium.com/@rajatmtr30/structural-patterns-in-java-practical-use-cases-82edbca80963?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/82edbca80963</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 11:02:28 GMT</pubDate>
            <atom:updated>2026-02-23T11:02:28.042Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>If creational patterns answer </em>“How are objects created?”<em><br>Structural patterns answer </em>“How are objects connected?”</blockquote><p>In real production systems, especially in Spring Boot microservices, complexity doesn’t come from creating objects — it comes from wiring them together correctly.</p><p>Structural patterns help you:</p><ul><li>Reduce tight coupling</li><li>Wrap external systems safely</li><li>Add behavior without modifying code</li><li>Simplify complex subsystems</li></ul><p>In this article, we’ll cover:</p><ul><li>Adapter (Integrating third-party APIs)</li><li>Decorator (Logging / Security)</li><li>Facade (Service layer design)</li><li>Proxy (Spring AOP)</li><li>Composite (Tree structures)</li></ul><p>And most importantly, how Spring internally uses these patterns.</p><h3>1️⃣ Adapter Pattern</h3><p><strong>Use Case: Integrating Third-Party APIs</strong></p><h3>The Problem</h3><p>You integrate a payment gateway.</p><p>Your system expects:</p><pre>public interface PaymentGateway {<br>    void pay(double amount);<br>}</pre><p>But third-party SDK gives:</p><pre>public class RazorpayClient {<br>    public void makePayment(double amountInRupees) {<br>        System.out.println(&quot;Paid using Razorpay&quot;);<br>    }<br>}</pre><p>You cannot modify their code.</p><h3>Solution: Adapter</h3><pre>public class RazorpayAdapter implements PaymentGateway {<br>private RazorpayClient razorpayClient;<br>    public RazorpayAdapter(RazorpayClient client) {<br>        this.razorpayClient = client;<br>    }<br>    @Override<br>    public void pay(double amount) {<br>        razorpayClient.makePayment(amount);<br>    }<br>}<br>// Now your system talks to PaymentGateway, not Razorpay directly.</pre><h3>Real Microservice Use Case</h3><ul><li>Integrating external KYC APIs</li><li>SMS providers</li><li>Payment providers</li><li>OAuth providers</li></ul><h3>How Spring Uses Adapter</h3><p>Spring MVC uses adapters internally:</p><p>HandlerAdapter allows different controller types to work uniformly.</p><p>You write:</p><pre>@RestController</pre><p>Spring adapts it internally to a common execution flow.</p><h3>2️⃣ Decorator Pattern</h3><p><strong>Use Case: Adding Logging / Security Without Changing Core Code</strong></p><h3>The Problem</h3><p>You want to add logging to a service.</p><p>Bad approach:</p><pre>public void processOrder() {<br>    System.out.println(&quot;Logging...&quot;);<br>    // business logic<br>}</pre><p>This pollutes business logic.</p><h3>Solution: Decorator</h3><p>Base interface:</p><pre>public interface OrderService {<br>    void processOrder();<br>}</pre><p>Concrete class:</p><pre>public class OrderServiceImpl implements OrderService {<br>    public void processOrder() {<br>        System.out.println(&quot;Processing order...&quot;);<br>    }<br>}</pre><p>Decorator:</p><pre>public class LoggingOrderService implements OrderService {<br>private OrderService orderService;<br>    public LoggingOrderService(OrderService orderService) {<br>        this.orderService = orderService;<br>    }<br>    @Override<br>    public void processOrder() {<br>        System.out.println(&quot;Logging before...&quot;);<br>        orderService.processOrder();<br>        System.out.println(&quot;Logging after...&quot;);<br>    }<br>}<br>//Now behavior is extended, not modified.</pre><h3>Real Microservice Use Case</h3><ul><li>Logging</li><li>Metrics collection</li><li>Authentication</li><li>Rate limiting</li></ul><h3>How Spring Uses Decorator</h3><p>Spring Security filter chain behaves like decorators.</p><p>Each filter wraps the request and passes it forward.</p><p>Also:</p><ul><li>HttpServletRequestWrapper</li><li>ResponseBodyAdvice</li></ul><p>These wrap and enhance behavior.</p><h3>3️⃣ Facade Pattern</h3><p><strong>Use Case: Simplifying Complex Subsystems</strong></p><h3>The Problem</h3><p>Your order flow requires:</p><ul><li>PaymentService</li><li>InventoryService</li><li>NotificationService</li><li>AuditService</li></ul><p>The controller becomes messy.</p><h3>Solution: Facade</h3><pre>public class OrderFacade {<br>private PaymentService paymentService;<br>    private InventoryService inventoryService;<br>    private NotificationService notificationService;<br>    public void placeOrder(Order order) {<br>        paymentService.pay(order);<br>        inventoryService.reserve(order);<br>        notificationService.notifyUser(order);<br>    }<br>}</pre><p>Controller now calls:</p><pre>orderFacade.placeOrder(order);</pre><p>Clean. Simple. Unified.</p><h3>Real Microservice Use Case</h3><ul><li>Service layer in Spring Boot</li><li>Orchestrating multiple downstream services</li><li>Aggregator APIs</li></ul><h3>How Spring Uses Facade</h3><p>JdbcTemplate is a classic example.</p><p>Instead of dealing with:</p><ul><li>Connection</li><li>Statement</li><li>ResultSet</li><li>Exception handling</li></ul><p>You just write:</p><pre>jdbcTemplate.query(&quot;SELECT * FROM users&quot;, rowMapper);</pre><p>That’s Facade.</p><h3>4️⃣ Proxy Pattern</h3><p><strong>Use Case: Spring AOP, Lazy Loading</strong></p><h3>The Problem</h3><p>You want to:</p><ul><li>Add transactions</li><li>Add security</li><li>Add logging</li></ul><p>Without changing business logic.</p><h3>Solution: Proxy</h3><p>Proxy controls access to the real object.</p><p>Manual example:</p><pre>public class PaymentServiceProxy implements PaymentService {<br>private PaymentService realService;<br>    public PaymentServiceProxy(PaymentService service) {<br>        this.realService = service;<br>    }<br>    @Override<br>    public void pay() {<br>        System.out.println(&quot;Checking security...&quot;);<br>        realService.pay();<br>    }<br>}</pre><h3>How Spring Uses Proxy</h3><p>When you write:</p><pre>@Transactional<br>public void processPayment() {}</pre><p>Spring creates a proxy around your bean.</p><p>That proxy:</p><ul><li>Opens transaction</li><li>Calls method</li><li>Commits/rolls back</li></ul><p>Same with:</p><ul><li>@Async</li><li>@Cacheable</li><li>@Secured</li></ul><p>Spring heavily relies on JDK dynamic proxies and CGLIB.</p><p>This is one of the most important real-world pattern usages.</p><h3>Microservice Use Case</h3><ul><li>Transaction management</li><li>Distributed tracing</li><li>Observability</li><li>Lazy loading (Hibernate proxies)</li></ul><h3>5️⃣ Composite Pattern</h3><p><strong>Use Case: Tree Structures</strong></p><h3>The Problem</h3><p>You want to represent hierarchical data:</p><ul><li>Organization structure</li><li>Folder system</li><li>Workflow steps</li></ul><p>Both individual objects and groups should be treated uniformly.</p><h3>Implementation</h3><p>Component:</p><pre>public interface FileSystemComponent {<br>    void showDetails();<br>}</pre><p>Leaf:</p><pre>public class File implements FileSystemComponent {<br>    public void showDetails() {<br>        System.out.println(&quot;File&quot;);<br>    }<br>}</pre><p>Composite:</p><pre>import java.util.List;<br>public class Folder implements FileSystemComponent {<br>    private List&lt;FileSystemComponent&gt; components;<br>    public Folder(List&lt;FileSystemComponent&gt; components) {<br>        this.components = components;<br>    }<br>    public void showDetails() {<br>        for(FileSystemComponent component : components) {<br>            component.showDetails();<br>        }<br>    }<br>}<br><br>// Now folder and file are treated the same.</pre><h3>Real Microservice Use Case</h3><ul><li>Menu hierarchies</li><li>Organization tree</li><li>Role-based permission tree</li><li>Nested workflow engine</li></ul><h3>How Spring Uses Composite</h3><p>Spring Security uses composite for:</p><ul><li>FilterChainProxy</li><li>Multiple security filters forming a chain</li></ul><p>Also:</p><ul><li>CompositeViewResolver</li><li>HandlerExceptionResolverComposite</li></ul><p>Spring often groups multiple implementations into one unified structure.</p><h3>Key Takeaways for Production Systems</h3><p>In microservices:</p><ul><li>Adapter protects you from third-party API changes</li><li>Decorator keeps business logic clean</li><li>Facade simplifies orchestration</li><li>Proxy powers AOP &amp; transactions</li><li>Composite handles hierarchical data</li></ul><p>Most importantly:</p><blockquote><em>If you are using Spring Boot, you are already using structural patterns daily — whether you realize it or not.</em></blockquote><p>Understanding these patterns makes you:</p><ul><li>Better at debugging</li><li>Better at architecture discussions</li><li>Better at interview explanations</li><li>Better at writing scalable code</li></ul><p>In the next article, we’ll move to <strong>Behavioral Patterns</strong> — where we design how objects communicate.</p><p>And that’s where systems truly become powerful.</p><p>Happy learning</p><p>Rajat Sharma</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82edbca80963" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creational Patterns in Java (With Real Examples)]]></title>
            <link>https://medium.com/@rajatmtr30/creational-patterns-in-java-with-real-examples-4bb4b69818de?source=rss-7faa42c577df------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb4b69818de</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Rajat Sharma]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 10:46:00 GMT</pubDate>
            <atom:updated>2026-02-21T10:46:00.842Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“How objects are created” sounds simple — until your application grows.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbmLw-f4iFwZ3CJdtCtjTA.gif" /></figure><p>In small projects, we casually use new.<br>In production systems, object creation becomes a design decision.</p><ul><li>Who controls the object lifecycle?</li><li>How do we ensure consistency?</li><li>How do we make object creation flexible?</li><li>How do we avoid tight coupling?</li></ul><p>That’s where <strong>Creational Design Patterns</strong> come in.</p><p>In this article, we’ll cover:</p><ul><li>Singleton (Thread-safe + Spring Bean)</li><li>Factory Method</li><li>Abstract Factory</li><li>Builder (Very important)</li><li>Prototype</li></ul><p>All with practical Java, Spring Boot, and microservice context.</p><h3>1️⃣ Singleton Pattern</h3><h3>What Problem Does It Solve?</h3><p>Ensure a class has only <strong>one instance</strong> and provide a global access point.</p><p>Common use cases:</p><ul><li>Configuration manager</li><li>Cache manager</li><li>Logger</li><li>Connection pool</li></ul><h3>Basic Singleton (Not Thread-Safe)</h3><pre>public class ConfigManager {<br>private static ConfigManager instance;<br>    private ConfigManager() {}<br>    public static ConfigManager getInstance() {<br>        if (instance == null) {<br>            instance = new ConfigManager();<br>        }<br>        return instance;<br>    }<br>}</pre><p>Problem: Not thread-safe.</p><p>Thread-Safe Singleton (Best Practice)</p><h3>Option 1: Bill Pugh Method (Recommended)</h3><pre>public class ConfigManager {<br>private ConfigManager() {}<br>    private static class Holder {<br>        private static final ConfigManager INSTANCE = new ConfigManager();<br>    }<br>    public static ConfigManager getInstance() {<br>        return Holder.INSTANCE;<br>    }<br>}</pre><p>This is:</p><ul><li>Thread-safe</li><li>Lazy loaded</li><li>Efficient</li></ul><h3>Singleton in Spring Boot</h3><p>In Spring:</p><pre>@Service<br>public class UserService {<br>}</pre><p>By default:</p><ul><li>Beans are singleton-scoped.</li><li>Spring manages the lifecycle.</li></ul><p>So in modern microservices:</p><blockquote><em>You rarely write manual Singleton — Spring already handles it.</em></blockquote><h3>Real Microservice Use Case</h3><ul><li>Shared Redis cache manager</li><li>Feature flag configuration</li><li>Token validator service</li></ul><h3>Interview Question</h3><p><strong>Q:</strong> Is Singleton always safe in distributed systems?<br><strong>Answer:</strong> No. Singleton is JVM-scoped. In microservices, each instance will have its own singleton.</p><h3>2️⃣ Factory Method Pattern</h3><h3>Problem</h3><p>You want to create objects without exposing creation logic.</p><p>Let’s revisit payment example.</p><p>Bad:</p><pre>if(type.equals(&quot;UPI&quot;)) {<br>    return new UpiPayment();<br>}</pre><p>Better approach:</p><h3>Implementation</h3><pre>public interface Payment {<br>    void pay(double amount);<br>}</pre><pre>public class UpiPayment implements Payment {<br>    public void pay(double amount) {<br>        System.out.println(&quot;Paid via UPI&quot;);<br>    }<br>}</pre><p>Factory:</p><pre>public abstract class PaymentFactory {<br>    public abstract Payment createPayment();<br>}</pre><p>Concrete factory:</p><pre>public class UpiPaymentFactory extends PaymentFactory {<br>    public Payment createPayment() {<br>        return new UpiPayment();<br>    }<br>}</pre><p>Now object creation is delegated.</p><h3>Spring Boot Version</h3><p>In Spring, we often implement a factory using:</p><pre>@Component<br>public class PaymentFactory {<br>public Payment getPayment(String type) {<br>        return switch (type) {<br>            case &quot;UPI&quot; -&gt; new UpiPayment();<br>            case &quot;CARD&quot; -&gt; new CardPayment();<br>            default -&gt; throw new IllegalArgumentException();<br>        };<br>    }<br>}</pre><p>Or better: Inject a map of beans.</p><h3>Microservice Use Case</h3><ul><li>Notification service (Email, SMS, Push)</li><li>Document signer types</li><li>Different authentication providers</li></ul><h3>Interview Question</h3><p><strong>Q:</strong> Difference between Factory and Strategy?<br>The factory creates objects. Strategy changes behavior dynamically.</p><h3>3️⃣ Abstract Factory Pattern</h3><h3>Problem</h3><p>You need families of related objects.</p><p>Example:<br>Payment system for:</p><ul><li>India</li><li>US</li></ul><p>Each region has:</p><ul><li>Payment processor</li><li>Tax calculator</li></ul><h3>Structure</h3><pre>public interface PaymentProcessor {<br>    void process();<br>}<br><br>public interface TaxCalculator {<br>    double calculateTax(double amount);<br>}</pre><p>Abstract factory:</p><pre>public interface FinancialFactory {<br>    PaymentProcessor createProcessor();<br>    TaxCalculator createTaxCalculator();<br>}</pre><p>Concrete factory:</p><pre>public class IndiaFactory implements FinancialFactory {<br>public PaymentProcessor createProcessor() {<br>        return new IndiaPaymentProcessor();<br>    }<br>    public TaxCalculator createTaxCalculator() {<br>        return new IndiaTaxCalculator();<br>    }<br>}</pre><p>Now switching countries changes the entire family.</p><h3>Real Microservice Example</h3><ul><li>Multi-tenant SaaS platform</li><li>Multi-region compliance rules</li><li>Different database providers</li></ul><h3>Interview Question</h3><p><strong>Q:</strong> Factory vs Abstract Factory?<br>The factory creates one product. Abstract Factory creates related families of products.</p><h3>4️⃣ Builder Pattern (Very Important)</h3><p>One of the most used patterns in modern Java.</p><h3>Problem</h3><p>Too many constructor parameters.</p><p>Bad:</p><pre>public User(String name, String email, String phone, String address, boolean active)</pre><p>Hard to read. Easy to break.</p><h3>Builder Implementation</h3><pre>public class User {<br>private String name;<br>    private String email;<br>    private String phone;<br>    private User(UserBuilder builder) {<br>        this.name = builder.name;<br>        this.email = builder.email;<br>        this.phone = builder.phone;<br>    }<br>    public static class UserBuilder {<br>        private String name;<br>        private String email;<br>        private String phone;<br>        public UserBuilder name(String name) {<br>            this.name = name;<br>            return this;<br>        }<br>        public UserBuilder email(String email) {<br>            this.email = email;<br>            return this;<br>        }<br>        public UserBuilder phone(String phone) {<br>            this.phone = phone;<br>            return this;<br>        }<br>        public User build() {<br>            return new User(this);<br>        }<br>    }<br>}</pre><p>Usage:</p><pre>User user = new User.UserBuilder()<br>        .name(&quot;Rajat&quot;)<br>        .email(&quot;rajat@email.com&quot;)<br>        .build();</pre><p>Clean. Readable. Immutable-friendly.</p><h3>Spring Boot Example</h3><p>Lombok simplifies this:</p><pre>@Builder<br>@Getter<br>public class UserDto {<br>    private String name;<br>    private String email;<br>}</pre><p>Used heavily in:</p><ul><li>REST DTOs</li><li>Kafka events</li><li>Request/Response models</li></ul><h3>Microservice Use Case</h3><ul><li>Creating complex request payloads</li><li>Event-driven architecture messages</li><li>Immutable domain models</li></ul><h3>Interview Question</h3><p><strong>Q:</strong> Why is Builder preferred in microservices?<br>Because APIs evolve, builders avoid constructor explosion.</p><h3>5️⃣ Prototype Pattern</h3><h3>Problem</h3><p>Object creation is expensive.</p><p>Instead of creating new objects, clone existing ones.</p><h3>Example</h3><pre>public class Document implements Cloneable {<br>private String content;<br>    public Document(String content) {<br>        this.content = content;<br>    }<br>    @Override<br>    protected Object clone() throws CloneNotSupportedException {<br>        return super.clone();<br>    }<br>}</pre><p>Usage:</p><pre>Document doc1 = new Document(&quot;Template&quot;);<br>Document doc2 = (Document) doc1.clone();</pre><h3>Real Use Case</h3><ul><li>Document template systems</li><li>Configuration snapshots</li><li>Workflow cloning</li><li>Game development</li></ul><h3>Microservice Scenario</h3><p>In a document signing platform:</p><ul><li>Clone workflow template</li><li>Modify participants</li><li>Keep the base template intact</li></ul><p>Creational patterns answer a simple but powerful question:</p><p><em>Who controls object creation?</em></p><p>In enterprise systems, controlling object creation:</p><ul><li>Reduces coupling</li><li>Improves flexibility</li><li>Makes scaling easier</li><li>Makes testing cleaner</li></ul><p>If you’re working with Spring Boot and microservices, you’re already using these patterns — sometimes without realizing it.</p><p>In the next article, we’ll explore <strong>Structural Patterns</strong> and how they shape real production systems.</p><p>If you’re serious about becoming a senior Java engineer, mastering creational patterns is not optional — it’s foundational.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb4b69818de" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>