<?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 Nilesh Gardas on Medium]]></title>
        <description><![CDATA[Stories by Nilesh Gardas on Medium]]></description>
        <link>https://medium.com/@nilesh.gardas?source=rss-caa0fda9090d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EqUAzBKaZA0etp-Y</url>
            <title>Stories by Nilesh Gardas on Medium</title>
            <link>https://medium.com/@nilesh.gardas?source=rss-caa0fda9090d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 20:33:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nilesh.gardas/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[In React, protected routes]]></title>
            <link>https://medium.com/@nilesh.gardas/in-react-protected-routes-4fee4b72d049?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fee4b72d049</guid>
            <category><![CDATA[protected-routes-in-react]]></category>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 08:25:18 GMT</pubDate>
            <atom:updated>2026-08-30T08:25:18.257Z</atom:updated>
            <content:encoded><![CDATA[<p>In React, protected routes are used to prevent unauthenticated users from accessing certain pages. The implementation depends on your routing library, but the most common approach is with React Router v6+.</p><h3>1. Create an authentication context</h3><pre>// AuthContext.jsx<br>import { createContext, useContext, useState } from &quot;react&quot;;<br><br>const AuthContext = createContext();<br>export function AuthProvider({ children }) {<br>  const [user, setUser] = useState(null);<br>  const login = (userData) =&gt; setUser(userData);<br>  const logout = () =&gt; setUser(null);<br>  return (<br>    &lt;AuthContext.Provider value={{ user, login, logout }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>}<br>export const useAuth = () =&gt; useContext(AuthContext);</pre><h3>2. Create a Protected Route component</h3><pre>// ProtectedRoute.jsx<br>import { Navigate, Outlet } from &quot;react-router-dom&quot;;<br>import { useAuth } from &quot;./AuthContext&quot;;<br><br>export default function ProtectedRoute() {<br>  const { user } = useAuth();<br>  return user ? &lt;Outlet /&gt; : &lt;Navigate to=&quot;/login&quot; replace /&gt;;<br>}</pre><h3>3. Configure routes</h3><pre>// App.jsx<br>import {<br>  BrowserRouter,<br>  Routes,<br>  Route,<br>} from &quot;react-router-dom&quot;;<br><br>import Home from &quot;./Home&quot;;<br>import Login from &quot;./Login&quot;;<br>import Dashboard from &quot;./Dashboard&quot;;<br>import Profile from &quot;./Profile&quot;;<br>import ProtectedRoute from &quot;./ProtectedRoute&quot;;<br>import { AuthProvider } from &quot;./AuthContext&quot;;<br>function App() {<br>  return (<br>    &lt;AuthProvider&gt;<br>      &lt;BrowserRouter&gt;<br>        &lt;Routes&gt;<br>          &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>          &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;<br>          {/* Protected Routes */}<br>          &lt;Route element={&lt;ProtectedRoute /&gt;}&gt;<br>            &lt;Route path=&quot;/dashboard&quot; element={&lt;Dashboard /&gt;} /&gt;<br>            &lt;Route path=&quot;/profile&quot; element={&lt;Profile /&gt;} /&gt;<br>          &lt;/Route&gt;<br>        &lt;/Routes&gt;<br>      &lt;/BrowserRouter&gt;<br>    &lt;/AuthProvider&gt;<br>  );<br>}<br>export default App;</pre><h3>4. Login example</h3><pre>// Login.jsx<br>import { useAuth } from &quot;./AuthContext&quot;;<br>import { useNavigate } from &quot;react-router-dom&quot;;<br><br>export default function Login() {<br>  const { login } = useAuth();<br>  const navigate = useNavigate();<br>  const handleLogin = () =&gt; {<br>    login({<br>      id: 1,<br>      name: &quot;John&quot;,<br>    });<br>    navigate(&quot;/dashboard&quot;);<br>  };<br>  return (<br>    &lt;button onClick={handleLogin}&gt;<br>      Login<br>    &lt;/button&gt;<br>  );<br>}</pre><h3>5. Persist authentication (recommended)</h3><p>Instead of storing the user only in state, save a token in localStorage or use secure HTTP-only cookies.</p><pre>// Login<br>localStorage.setItem(&quot;token&quot;, &quot;jwt-token&quot;);</pre><pre>// ProtectedRoute<br>const token = localStorage.getItem(&quot;token&quot;);<br><br>return token ? &lt;Outlet /&gt; : &lt;Navigate to=&quot;/login&quot; replace /&gt;;</pre><blockquote><em>For production applications, HTTP-only cookies are generally more secure than storing JWTs in </em><em>localStorage, as they help mitigate XSS attacks.</em></blockquote><h3>6. Protect based on roles (optional)</h3><pre>import { Navigate, Outlet } from &quot;react-router-dom&quot;;<br>import { useAuth } from &quot;./AuthContext&quot;;<br><br>export default function AdminRoute() {<br>  const { user } = useAuth();<br>  if (!user) {<br>    return &lt;Navigate to=&quot;/login&quot; replace /&gt;;<br>  }<br>  if (user.role !== &quot;admin&quot;) {<br>    return &lt;Navigate to=&quot;/unauthorized&quot; replace /&gt;;<br>  }<br>  return &lt;Outlet /&gt;;<br>}</pre><p>Usage:</p><pre>&lt;Route element={&lt;AdminRoute /&gt;}&gt;<br>  &lt;Route path=&quot;/admin&quot; element={&lt;AdminDashboard /&gt;} /&gt;<br>&lt;/Route&gt;</pre><h4>Alternative: Wrapper Component</h4><p>Instead of using Outlet, you can wrap individual components:</p><pre>function ProtectedRoute({ children }) {<br>  const token = localStorage.getItem(&quot;token&quot;);<br>  <br>  return token ? children : &lt;Navigate to=&quot;/login&quot; replace /&gt;;<br>}</pre><p>Usage:</p><pre>&lt;Route<br>  path=&quot;/dashboard&quot;<br>  element={<br>    &lt;ProtectedRoute&gt;<br>      &lt;Dashboard /&gt;<br>    &lt;/ProtectedRoute&gt;<br>  }<br>/&gt;</pre><h4>Best practices</h4><ul><li>Keep authentication state in a context or state management library (Redux, Zustand, etc.).</li><li>Verify JWTs or sessions on the backend; don’t rely solely on client-side checks.</li><li>Persist sessions securely (prefer HTTP-only cookies when possible).</li><li>Handle loading states while checking authentication (e.g., validating a token with the server) to avoid redirect flicker.</li><li>==========</li></ul><h3>Q. what about authorizations checks</h3><p>Yes. Authentication answers “is the user logged in?”, while authorization answers “is this logged-in user allowed to do this?”</p><p>A clean React Router setup is to make authorization a layer on top of your protected routes.</p><h4>Role-based authorization</h4><p>For example, suppose your user looks like:</p><pre>{<br>  id: 123,<br>  name: &quot;John&quot;,<br>  role: &quot;admin&quot;<br>}</pre><p>You can create a reusable RequireRole component:</p><pre>import { Navigate, Outlet } from &quot;react-router-dom&quot;;<br>import { useAuth } from &quot;./AuthContext&quot;;<br><br>export default function RequireRole({ allowedRoles }) {<br>  const { user } = useAuth();<br>  if (!user) {<br>    return &lt;Navigate to=&quot;/login&quot; replace /&gt;;<br>  }<br>  if (!allowedRoles.includes(user.role)) {<br>    return &lt;Navigate to=&quot;/unauthorized&quot; replace /&gt;;<br>  }<br>  return &lt;Outlet /&gt;;<br>}</pre><p>Then your routes can be structured like this:</p><pre>&lt;Routes&gt;<br>  &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;<br><br>  {/* Any logged-in user */}<br>  &lt;Route element={&lt;ProtectedRoute /&gt;}&gt;<br>    &lt;Route path=&quot;/dashboard&quot; element={&lt;Dashboard /&gt;} /&gt;<br>    &lt;Route path=&quot;/profile&quot; element={&lt;Profile /&gt;} /&gt;<br>    {/* Admin only */}<br>    &lt;Route element={&lt;RequireRole allowedRoles={[&quot;admin&quot;]} /&gt;}&gt;<br>      &lt;Route path=&quot;/admin&quot; element={&lt;AdminDashboard /&gt;} /&gt;<br>      &lt;Route path=&quot;/users&quot; element={&lt;UserManagement /&gt;} /&gt;<br>    &lt;/Route&gt;<br>    {/* Admin or manager */}<br>    &lt;Route<br>      element={<br>        &lt;RequireRole allowedRoles={[&quot;admin&quot;, &quot;manager&quot;]} /&gt;<br>      }<br>    &gt;<br>      &lt;Route path=&quot;/reports&quot; element={&lt;Reports /&gt;} /&gt;<br>    &lt;/Route&gt;<br>  &lt;/Route&gt;<br>  &lt;Route path=&quot;/unauthorized&quot; element={&lt;Unauthorized /&gt;} /&gt;<br>&lt;/Routes&gt;<br></pre><p>This gives you:</p><pre>/login<br>   ↓<br>ProtectedRoute<br>   ↓<br>Is user authenticated?<br>   ├── No  → /login<br>   └── Yes<br>        ↓<br>    RequireRole<br>        ↓<br>    Is role allowed?<br>        ├── No  → /unauthorized<br>        └── Yes → Page</pre><h3>Permission-based authorization</h3><p>For a larger application, permissions are often better than roles.</p><p>Instead of:</p><pre>user.role === &quot;admin&quot;</pre><p>you might have:</p><pre>user.permissions = [<br>  &quot;users:read&quot;,<br>  &quot;users:create&quot;,<br>  &quot;users:update&quot;,<br>  &quot;reports:read&quot;<br>];</pre><p>Then create:</p><pre>function RequirePermission({ permission }) {<br>  const { user } = useAuth();<br><br>  if (!user) {<br>    return &lt;Navigate to=&quot;/login&quot; replace /&gt;;<br>  }<br>  if (!user.permissions.includes(permission)) {<br>    return &lt;Navigate to=&quot;/unauthorized&quot; replace /&gt;;<br>  }<br>  return &lt;Outlet /&gt;;<br>}</pre><p>Routes:</p><pre>&lt;Route element={&lt;ProtectedRoute /&gt;}&gt;<br>  &lt;Route<br>    element={&lt;RequirePermission permission=&quot;reports:read&quot; /&gt;}<br>  &gt;<br>    &lt;Route path=&quot;/reports&quot; element={&lt;Reports /&gt;} /&gt;<br>  &lt;/Route&gt;<br><br>  &lt;Route<br>    element={&lt;RequirePermission permission=&quot;users:create&quot; /&gt;}<br>  &gt;<br>    &lt;Route path=&quot;/users/new&quot; element={&lt;CreateUser /&gt;} /&gt;<br>  &lt;/Route&gt;<br>&lt;/Route&gt;<br></pre><p>This scales better because you can have roles such as:</p><pre>admin<br>manager<br>support<br>analyst</pre><p>while independently controlling what each role can do.</p><h3>But there’s an important security point</h3><p>React authorization is not security.</p><p>A user can open DevTools and potentially navigate directly to:</p><pre>/admin</pre><p>or modify JavaScript/state in the browser.</p><p>Your backend/API must perform the authorization check too:</p><pre>React<br>  ↓<br>&quot;Can I show this button?&quot;<br>  ↓<br>API request<br>  ↓<br>Backend<br>  ↓<br>&quot;Does this user actually have users:create?&quot;<br>  ↓<br>Allow / 403 Forbidden</pre><p>So use frontend authorization primarily for UI/UX, while the backend is the actual security boundary.</p><p>For example:</p><pre>{user.permissions.includes(&quot;users:delete&quot;) &amp;&amp; (<br>  &lt;button onClick={deleteUser}&gt;<br>    Delete User<br>  &lt;/button&gt;<br>)}</pre><p>But your API must still reject:</p><pre>DELETE /api/users/123</pre><p>with 403 Forbidden if the user doesn&#39;t have users:delete.</p><h3>A good architecture</h3><p>For a serious app, I’d generally use:</p><pre>AuthProvider<br>    │<br>    ├── user<br>    ├── isAuthenticated<br>    ├── permissions<br>    └── loading<br>          │<br>          ▼<br>   ProtectedRoute<br>          │<br>          ▼<br>   Authorization<br>   ├── RequireRole<br>   └── RequirePermission<br>          │<br>          ▼<br>       Page</pre><p>And keep the backend authorization rules as the source of truth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fee4b72d049" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Spring boot application in AWS EKS -Basic setup]]></title>
            <link>https://medium.com/@nilesh.gardas/deploy-spring-boot-application-in-aws-eks-basic-setup-ad567fec3970?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad567fec3970</guid>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 18:37:57 GMT</pubDate>
            <atom:updated>2026-08-20T18:37:57.372Z</atom:updated>
            <content:encoded><![CDATA[<p>Absolutely. Since you are new to AWS, I would <strong>not</strong> start with a complicated production architecture. Let’s first get your basic Spring Boot CRUD application running on EKS, understand what each AWS/Kubernetes component does, and then we can improve it.</p><p>The overall journey is:</p><pre>Your Spring Boot CRUD App<br>        │<br>        ▼<br>   Docker Image<br>        │<br>        ▼<br>Amazon ECR<br>        │<br>        ▼<br>Amazon EKS Cluster<br>        │<br>        ├── Kubernetes Deployment<br>        │       └── Spring Boot Pod(s)<br>        │<br>        └── Kubernetes Service<br>                │<br>                ▼<br>          Public Load Balancer<br>                │<br>                ▼<br>        http://your-api-url</pre><p>AWS describes EKS as a managed Kubernetes service, and its eksctl getting-started flow is currently the simplest way to create an initial EKS cluster. (<a href="https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html?utm_source=chatgpt.com">AWS Documentation</a>)</p><h3>1. First understand what we’re building</h3><p>Suppose your Spring Boot project looks like:</p><pre>employee-api/<br>├── src/<br>├── pom.xml<br>└── ...</pre><p>and locally you can do:</p><pre>mvn spring-boot:run</pre><p>and access:</p><pre>http://localhost:8080/employees</pre><p>We are going to turn that into:</p><pre>Spring Boot<br>     │<br>     │ Docker<br>     ▼<br>Docker Image<br>     │<br>     │ push<br>     ▼<br>Amazon ECR<br>     │<br>     │ pull<br>     ▼<br>Amazon EKS<br>     │<br>     ├── Pod 1<br>     ├── Pod 2<br>     └── Pod 3<br>     │<br>     ▼<br>Kubernetes Service<br>     │<br>     ▼<br>AWS Load Balancer<br>     │<br>     ▼<br>Internet</pre><p>Spring Boot officially supports creating container images using either <strong>Dockerfiles </strong>or Cloud Native <strong>Buildpacks</strong>. (<a href="https://docs.spring.io/spring-boot/reference/packaging/container-images/?utm_source=chatgpt.com">Home</a>)</p><h3>2. What AWS services do we need?</h3><p>For our first deployment, you’ll encounter these:</p><pre>| Technology        | Purpose                                     |<br>| ----------------- | ------------------------------------------- |<br>| **AWS**           | Cloud platform                              |<br>| **EKS**           | Kubernetes cluster                          |<br>| **EC2 Nodes**     | Machines running your Pods                  |<br>| **ECR**           | Stores Docker images                        |<br>| **IAM**           | Permissions and security                    |<br>| **VPC**           | AWS networking                              |<br>| **Load Balancer** | Makes your API accessible from the Internet |<br>| **kubectl**       | Talks to Kubernetes                         |<br>| **eksctl**        | Creates and manages EKS clusters            |<br>| **Docker**        | Creates container images                    |</pre><p>Don’t worry if these terms seem confusing now. We’ll learn them while deploying.</p><h3>3. Prerequisites on your laptop</h3><p>You need:</p><h3>Required</h3><ol><li>AWS account</li><li>AWS CLI</li><li>Docker</li><li>kubectl</li><li>eksctl</li><li>Java</li><li>Maven</li></ol><p>AWS’s EKS documentation lists AWS CLI, kubectl, and eksctl as prerequisites for the eksctl approach. (<a href="https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html?utm_source=chatgpt.com">AWS Documentation</a>)</p><p>Check them:</p><pre>aws --version</pre><pre>docker --version</pre><pre>kubectl version --client</pre><pre>eksctl version</pre><pre>java -version</pre><pre>mvn -version</pre><p>If any command isn’t found, install that tool first.</p><h3>4. Configure AWS CLI</h3><p>After creating your AWS account, you’ll need AWS credentials for your CLI.</p><p>Run:</p><pre>aws configure</pre><p>It will ask:</p><pre>AWS Access Key ID:<br>AWS Secret Access Key:<br>Default region name:<br>Default output format:</pre><p>For example, you might use:</p><pre>AWS Access Key ID: ********<br>AWS Secret Access Key: ********<br>Default region name: ap-south-1<br>Default output format: json</pre><p>Since you’re likely deploying from India, <strong>ap-south-1 (Mumbai)</strong> is a reasonable region to start with.</p><p>Verify:</p><pre>aws sts get-caller-identity</pre><p>You should get something resembling:</p><pre>{<br>    &quot;UserId&quot;: &quot;...&quot;,<br>    &quot;Account&quot;: &quot;123456789012&quot;,<br>    &quot;Arn&quot;: &quot;arn:aws:iam::123456789012:user/...&quot;<br>}</pre><h3>5. First make sure your Spring Boot application works</h3><p>Before touching AWS, run your application locally.</p><p>For Maven:</p><pre>mvn clean package</pre><p>You should see:</p><pre>BUILD SUCCESS</pre><p>Then:</p><pre>java -jar target/your-application.jar</pre><p>Test your CRUD APIs.</p><p>For example:</p><pre>GET     /employees<br>GET     /employees/1<br>POST    /employees<br>PUT     /employees/1<br>DELETE  /employees/1</pre><p><strong>Important:</strong> Get the application working locally first.</p><p>Don’t try to debug Spring Boot + Docker + Kubernetes + AWS simultaneously.</p><h3>6. Containerize your Spring Boot application</h3><p>Now we’re going to create a Docker image.</p><p>At the root of your project:</p><pre>employee-api/<br>├── src/<br>├── pom.xml<br>└── Dockerfile       &lt;-- create this</pre><p>Create:</p><pre>FROM eclipse-temurin:21-jre<br><br>WORKDIR /app<br><br>COPY target/*.jar app.jar<br><br>EXPOSE 8080<br><br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>If you’re using Java 17, use:</p><pre>FROM eclipse-temurin:17-jre</pre><p>instead.</p><p>Then build your Spring Boot application:</p><pre>mvn clean package</pre><p>Build Docker image:</p><pre>docker build -t employee-api:1.0 .</pre><p>Check:</p><pre>docker images</pre><p>You should see something like:</p><pre>REPOSITORY      TAG       IMAGE ID<br>employee-api    1.0       abc123</pre><h3>7. Test Docker locally</h3><p>This step is important.</p><p>Run:</p><pre>docker run -p 8080:8080 employee-api:1.0</pre><p>Now access:</p><pre>http://localhost:8080</pre><p>or your API:</p><pre>http://localhost:8080/employees</pre><p>If your CRUD API works, excellent.</p><p>Now we know:</p><pre>Spring Boot<br>    ↓<br>Docker<br>    ↓<br>Working</pre><p>Spring’s official Docker guide follows the same basic concept: package the Spring Boot application into a container and expose port 8080. (<a href="https://spring.io/guides/gs/spring-boot-docker/?source=your_stories_page---------------------------&amp;utm_source=chatgpt.com">Home</a>)</p><h3>8. Create an ECR repository</h3><p>Now we need somewhere in AWS to store our Docker image.</p><p>That is <strong>Amazon ECR — Elastic Container Registry</strong>.</p><p>Think of it as:</p><pre>Docker Hub<br>     ≈<br>Amazon ECR</pre><p>but integrated with AWS.</p><p>Create repository:</p><pre>aws ecr create-repository \<br>  --repository-name employee-api \<br>  --region ap-south-1</pre><p>You’ll get information containing a URI similar to:</p><pre>123456789012.dkr.ecr.ap-south-1.amazonaws.com/employee-api</pre><p>We’ll call this:</p><pre>ECR_URI</pre><h3>9. Login Docker to ECR</h3><p>Run:</p><pre>aws ecr get-login-password --region ap-south-1 | \<br>docker login --username AWS --password-stdin \<br>123456789012.dkr.ecr.ap-south-1.amazonaws.com</pre><p>You should see:</p><pre>Login Succeeded</pre><h3>10. Tag your Docker image</h3><p>Currently your image is:</p><pre>employee-api:1.0</pre><p>We need to give it the ECR address.</p><pre>docker tag employee-api:1.0 \<br>123456789012.dkr.ecr.ap-south-1.amazonaws.com/employee-api:1.0</pre><p>Check:</p><pre>docker images</pre><p>You’ll see:</p><pre>employee-api                                      1.0<br>123456789012.dkr.ecr.ap-south-1.amazonaws.com/employee-api  1.0</pre><h3>11. Push Docker image to ECR</h3><p>Now:</p><pre>docker push \<br>123456789012.dkr.ecr.ap-south-1.amazonaws.com/employee-api:1.0</pre><p>You’ll see layers being uploaded:</p><pre>Preparing<br>Waiting<br>Pushed<br>...<br>1.0: digest: sha256:...</pre><p>Now your architecture is:</p><pre>Your Laptop<br>     │<br>     │ docker push<br>     ▼<br>┌─────────────────────┐<br>│     Amazon ECR      │<br>│                     │<br>│    employee-api     │<br>│        :1.0         │<br>└─────────────────────┘</pre><h3>12. Create your EKS cluster</h3><p>Now comes the major AWS part.</p><p>Instead of manually creating dozens of AWS resources, we’ll use <strong>eksctl</strong>.</p><p>AWS specifically describes eksctl as the simple CLI utility for creating and managing EKS clusters, and its getting-started guide calls this the fastest/simple approach for beginners.</p><p>Run:</p><pre>eksctl create cluster \<br>  --name springboot-cluster \<br>  --region ap-south-1 \<br>  --nodes 2</pre><p>This will create a lot of infrastructure for you.</p><p>Conceptually:</p><pre>AWS<br>│<br>└── EKS Cluster<br>      │<br>      ├── Worker Node<br>      │     ├── Pod<br>      │     └── Pod<br>      │<br>      └── Worker Node<br>            ├── Pod<br>            └── Pod</pre><p>Cluster creation can take several minutes. AWS’s current getting-started guide notes that eksctl creates the required resources and configures your local kubectl context. (<a href="https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html?utm_source=chatgpt.com">AWS Documentation</a>)</p><h3>13. Verify EKS</h3><p>Run:</p><pre>eksctl get cluster</pre><p>You should see:</p><pre>NAME                 REGION<br>springboot-cluster   ap-south-1</pre><p>Now:</p><pre>kubectl get nodes</pre><p>You should get something like:</p><pre>NAME                                         STATUS   ROLES<br>ip-10-0-1-123.ap-south-1.compute.internal   Ready    &lt;none&gt;<br>ip-10-0-2-456.ap-south-1.compute.internal   Ready    &lt;none&gt;</pre><p>The important part is:</p><pre>STATUS<br>Ready</pre><p>AWS’s EKS tutorial likewise uses kubectl get nodes -o wide to verify that the cluster nodes are ready. (<a href="https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html?utm_source=chatgpt.com">AWS Documentation</a>)</p><h3>14. Now we enter Kubernetes</h3><p>This is where many beginners get confused.</p><p>There are two important Kubernetes concepts initially:</p><h3>Deployment</h3><p>Tells Kubernetes:</p><blockquote><em>“Run my Spring Boot application.”</em></blockquote><h3>Service</h3><p>Tells Kubernetes:</p><blockquote><em>“Give my application a stable network endpoint.”</em></blockquote><p>We’ll create both.</p><h3>15. Create Kubernetes Deployment</h3><p>Create a directory:</p><pre>k8s/</pre><p>Inside it:</p><pre>k8s/<br>├── deployment.yaml<br>└── service.yaml</pre><p>deployment.yaml:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br><br>metadata:<br>  name: employee-api<br><br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: employee-api<br>  <br>  template:<br>    metadata:<br>      labels:<br>        app: employee-api<br><br>    spec:<br>      containers:<br>        - name: employee-api<br><br>          image: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/employee-api:1.0<br><br>          ports:<br>            - containerPort: 8080</pre><p>Replace:</p><pre>123456789012</pre><p>with your AWS account ID.</p><h3>16. What does this YAML mean?</h3><p>This:</p><pre>kind: Deployment</pre><p>means we’re creating a Kubernetes Deployment.</p><p>This:</p><pre>replicas: 2</pre><p>means:</p><blockquote><em>Run 2 copies of my Spring Boot application.</em></blockquote><p>So Kubernetes will create:</p><pre>Deployment<br>    │<br>    ├── Pod 1<br>    │     └── Spring Boot<br>    │<br>    └── Pod 2<br>          └── Spring Boot</pre><p>If one Pod dies, Kubernetes can create another.</p><p>That’s one of the major benefits of Kubernetes.</p><h3>17. Deploy it</h3><p>Run:</p><pre>kubectl apply -f k8s/deployment.yaml</pre><p>You should get:</p><pre>deployment.apps/employee-api created</pre><p>Check:</p><pre>kubectl get deployments</pre><p>You might see:</p><pre>NAME           READY   UP-TO-DATE   AVAILABLE<br>employee-api   2/2     2            2</pre><p>Now:</p><pre>kubectl get pods</pre><p>Something like:</p><pre>NAME                            READY   STATUS<br>employee-api-7f8d9c5d4-x7abc    1/1     Running<br>employee-api-7f8d9c5d4-p9xyz    1/1     Running</pre><p>This is a <strong>huge milestone</strong>.</p><p>Your Spring Boot application is now running inside EKS.</p><p>AWS’s own sample EKS deployment follows the same Deployment → Pods model.</p><h3>18. But there is one problem</h3><p>Your application is running, but you can’t access it from the Internet yet.</p><p>Currently:</p><pre>Internet<br>   ❌<br>   │<br>   ▼<br>Spring Boot Pod</pre><p>We need a Kubernetes <strong>Service</strong>.</p><h3>19. Create a LoadBalancer Service</h3><p>Create:</p><pre>k8s/service.yaml</pre><p>with:</p><pre>apiVersion: v1<br>kind: Service<br><br>metadata:<br>  name: employee-api-service<br><br>spec:<br>  type: LoadBalancer<br><br>  selector:<br>    app: employee-api<br><br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 8080</pre><p>The important part is:</p><pre>type: LoadBalancer</pre><p>This tells Kubernetes/AWS that we want an externally accessible load-balancing endpoint.</p><h3>20. Deploy the Service</h3><p>Run:</p><pre>kubectl apply -f k8s/service.yaml</pre><p>Then:</p><pre>kubectl get services</pre><p>Initially you may see:</p><pre>NAME                   TYPE           EXTERNAL-IP<br>employee-api-service   LoadBalancer   &lt;pending&gt;</pre><p>Wait a little while.</p><p>Run again:</p><pre>kubectl get services</pre><p>Eventually you’ll see something like:</p><pre>NAME                   TYPE           EXTERNAL-IP<br>employee-api-service   LoadBalancer   abc123.ap-south-1.elb.amazonaws.com</pre><p>That DNS name is your public endpoint.</p><h3>21. Access your Spring Boot API</h3><p>Suppose Kubernetes gives you:</p><pre>abc123.ap-south-1.elb.amazonaws.com</pre><p>Then:</p><pre>http://abc123.ap-south-1.elb.amazonaws.com/employees</pre><p>Your request travels approximately like this:</p><pre>AWS<br>                  │<br>                  ▼<br>       ┌───────────────────┐<br>       │   Load Balancer   │<br>       └─────────┬─────────┘<br>                 │<br>          Kubernetes Service<br>                 │<br>          ┌──────┴──────┐<br>          ▼             ▼<br>       Pod 1          Pod 2<br>          │             │<br>          ▼             ▼<br>      Spring Boot   Spring Boot</pre><p>Congratulations — your Spring Boot CRUD application is now accessible through AWS EKS.</p><h3>22. The complete deployment process</h3><p>You should memorize this flow:</p><pre>DEVELOPMENT<br>                  │<br>                  ▼<br>        ┌──────────────────┐<br>        │  Spring Boot App │<br>        └────────┬─────────┘<br>                 │<br>                 │ mvn package<br>                 ▼<br>        ┌──────────────────┐<br>        │    JAR file      │<br>        └────────┬─────────┘<br>                 │<br>                 │ docker build<br>                 ▼<br>        ┌──────────────────┐<br>        │   Docker Image   │<br>        └────────┬─────────┘<br>                 │<br>                 │ docker push<br>                 ▼<br>        ┌──────────────────┐<br>        │   Amazon ECR     │<br>        └────────┬─────────┘<br>                 │<br>                 │ Kubernetes pulls image<br>                 ▼<br>        ┌──────────────────┐<br>        │    Amazon EKS    │<br>        └────────┬─────────┘<br>                 │<br>                 ▼<br>        ┌──────────────────┐<br>        │    Deployment    │<br>        └────────┬─────────┘<br>                 │<br>           ┌─────┴─────┐<br>           ▼           ▼<br>         Pod 1       Pod 2<br>           │           │<br>           └─────┬─────┘<br>                 ▼<br>          Kubernetes Service<br>                 │<br>                 ▼<br>           Load Balancer<br>                 │<br>                 ▼<br>              Internet</pre><h3>23. Commands you’ll use frequently</h3><p>After everything is configured, your normal deployment process becomes approximately:</p><h3>Build application</h3><pre>mvn clean package</pre><h3>Build Docker image</h3><pre>docker build -t employee-api:1.1 .</pre><h3>Tag image</h3><pre>docker tag employee-api:1.1 \<br>123456789012.dkr.ecr.ap-south-1.amazonaws.com/employee-api:1.1</pre><h3>Push</h3><pre>docker push \<br>123456789012.dkr.ecr.ap-south-1.amazonaws.com/employee-api:1.1</pre><h3>Update Kubernetes</h3><p>Change:</p><pre>image: .../employee-api:1.1</pre><p>Then:</p><pre>kubectl apply -f k8s/deployment.yaml</pre><p>Check:</p><pre>kubectl get pods</pre><h3>24. Very important: Your database</h3><p>There’s one thing we haven’t covered yet.</p><p>Your CRUD application probably uses something like:</p><pre>Spring Boot<br>     │<br>     ▼<br>MySQL/PostgreSQL</pre><p><strong>Don’t put your production database inside a normal Kubernetes Pod for your first AWS deployment.</strong></p><p>A much better beginner AWS architecture is:</p><pre>AWS<br>                     │<br>           ┌─────────┴─────────┐<br>           │                   │<br>           ▼                   ▼<br>         EKS                 RDS<br>           │                   │<br>      Spring Boot          PostgreSQL<br>        Pods                 / MySQL<br>           │                   ▲<br>           └───────────────────┘</pre><p>Use <strong>Amazon RDS</strong> for the relational database.</p><p>Then configure Spring Boot:</p><pre>spring.datasource.url=jdbc:postgresql://YOUR-RDS-ENDPOINT:5432/employeedb<br>spring.datasource.username=...<br>spring.datasource.password=...</pre><p>Later, we’ll improve this by putting credentials into Kubernetes Secrets rather than keeping passwords in application.properties.</p><h3>25. Your first version vs production version</h3><p>Don’t try to build the final production architecture immediately.</p><h3>Stage 1 — Learning</h3><pre>Spring Boot<br>     ↓<br>Docker<br>     ↓<br>ECR<br>     ↓<br>EKS<br>     ↓<br>LoadBalancer</pre><p>This is what I recommend you do first.</p><h3>Stage 2 — Database</h3><pre>EKS<br>              │<br>       Spring Boot Pods<br>              │<br>              ▼<br>             RDS</pre><h3>Stage 3 — Production</h3><p>Eventually:</p><pre>Route 53<br>                       │<br>                       ▼<br>                  Load Balancer<br>                       │<br>                       ▼<br>                  EKS Cluster<br>                       │<br>          ┌────────────┼────────────┐<br>          ▼            ▼            ▼<br>        Pod 1        Pod 2        Pod 3<br>          │            │            │<br>          └────────────┼────────────┘<br>                       │<br>                       ▼<br>                      RDS</pre><pre>Additional:<br>├── IAM<br>├── Secrets Manager<br>├── CloudWatch<br>├── Auto Scaling<br>├── HTTPS<br>├── Route 53<br>├── CI/CD<br>└── Monitoring</pre><h3>26. Don’t worry about Kubernetes internals yet</h3><p>As a beginner, focus on these five things:</p><h3>1. Image</h3><pre>Docker Image</pre><p>Your Spring Boot application packaged for running anywhere.</p><h3>2. ECR</h3><pre>ECR</pre><p>AWS storage for your Docker image.</p><h3>3. Pod</h3><pre>Pod</pre><p>Where your Spring Boot container actually runs.</p><h3>4. Deployment</h3><pre>Deployment</pre><p>Controls how many Pods should exist.</p><h3>5. Service</h3><pre>Service</pre><p>Provides networking/access to your Pods.</p><p>If you understand those five concepts, EKS becomes much easier.</p><h3>27. One thing I recommend changing later</h3><p>Don’t use:</p><pre>image: ...:latest</pre><p>for your deployments.</p><p>Instead use versions:</p><pre>image: .../employee-api:1.0</pre><p>then:</p><pre>image: .../employee-api:1.1</pre><p>then:</p><pre>image: .../employee-api:1.2</pre><p>This makes deployments and rollbacks much easier.</p><p>Kubernetes can then perform a rolling update:</p><pre>Old version<br><br>Pod 1 → v1.0<br>Pod 2 → v1.0<br><br>       ↓ deployment<br><br>Pod 1 → v1.1<br>Pod 2 → v1.0<br><br>       ↓<br><br>Pod 1 → v1.1<br>Pod 2 → v1.1</pre><h3>28. How I suggest we learn this</h3><p>Rather than dumping 50 AWS concepts on you at once, I’d do this as a <strong>hands-on project</strong>.</p><h3>Lesson 1 — Local</h3><pre>Spring Boot<br>    ↓<br>Docker<br>    ↓<br>localhost</pre><h3>Lesson 2 — AWS ECR</h3><pre>Docker<br>    ↓<br>ECR</pre><h3>Lesson 3 — EKS</h3><pre>Create EKS<br>    ↓<br>kubectl<br>    ↓<br>Pods</pre><h3>Lesson 4 — Deploy Spring Boot</h3><pre>ECR<br> ↓<br>EKS<br> ↓<br>Deployment<br> ↓<br>Pods</pre><h3>Lesson 5 — Expose API</h3><pre>Pods<br> ↓<br>Service<br> ↓<br>AWS Load Balancer<br> ↓<br>Internet</pre><h3>Lesson 6 — Database</h3><pre>EKS<br> ↓<br>Spring Boot<br> ↓<br>RDS PostgreSQL/MySQL</pre><h3>Lesson 7 — Configuration &amp; Secrets</h3><pre>Kubernetes ConfigMap<br>Kubernetes Secret</pre><h3>Lesson 8 — HTTPS + domain</h3><pre>api.example.com<br>       ↓<br>HTTPS<br>       ↓<br>Load Balancer<br>       ↓<br>EKS</pre><h3>Lesson 9 — CI/CD</h3><p>Eventually:</p><pre>Developer<br>   │<br>   ▼<br>GitHub<br>   │<br>   ▼<br>GitHub Actions<br>   │<br>   ├── Build<br>   ├── Test<br>   ├── Docker build<br>   ├── Push ECR<br>   └── Deploy EKS</pre><p>So after that, you won’t manually run all those commands every time.</p><h3>Your immediate goal</h3><p>For your <strong>first deployment</strong>, don’t worry about RDS, HTTPS, Route 53, CI/CD, monitoring, Helm, Ingress, etc.</p><p>Get this working first:</p><pre>Spring Boot CRUD<br>      ↓<br>Docker<br>      ↓<br>ECR<br>      ↓<br>EKS<br>      ↓<br>Deployment<br>      ↓<br>2 Pods<br>      ↓<br>LoadBalancer<br>      ↓<br>Public API</pre><p>That’s the perfect first EKS project.</p><h3>Official references</h3><ul><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html?utm_source=chatgpt.com">AWS EKS getting started with eksctl</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/sample-deployment.html?utm_source=chatgpt.com">AWS EKS sample application deployment</a></li><li><a href="https://docs.spring.io/spring-boot/reference/packaging/container-images/?utm_source=chatgpt.com">Spring Boot container images documentation</a></li><li><a href="https://spring.io/guides/gs/spring-boot-docker/?source=your_stories_page---------------------------&amp;utm_source=chatgpt.com">Spring Boot Docker getting-started guide</a></li></ul><p><strong>If you want, send me your </strong><strong>pom.xml (and tell me whether you&#39;re using Java 17 or 21). I can take your actual Spring Boot CRUD project and walk you through the deployment from Step 1, including the exact </strong><strong>Dockerfile, ECR commands, </strong><strong>deployment.yaml, </strong><strong>service.yaml, and AWS commands for your project.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad567fec3970" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<Scenario> Making a call to 4 external API Parallelly, how can I aggregate the response into one ?]]></title>
            <link>https://medium.com/@nilesh.gardas/scenario-making-a-call-to-4-external-api-parallelly-how-can-i-aggregate-the-response-into-one-02c55c94cb28?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/02c55c94cb28</guid>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 18:50:50 GMT</pubDate>
            <atom:updated>2026-08-17T18:50:50.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>&lt;Scenario&gt; Making a call to 4 external API Parallelly, how can I aggregate the response into one ? — CompletableFuture/ Webclient/flux</h3><h3>1. Parallel Request calls :</h3><pre>import java.util.List;<br>import java.util.concurrent.CompletableFuture;<br><br>public class ParallelRequests {<br>    public static void main(String[] args) {<br>      // ⭐ NEW: Create ExecutorService<br>        ExecutorService executor = Executors.newFixedThreadPool(3);<br>        List&lt;String&gt; ids = List.of(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;);<br>       List&lt;CompletableFuture&lt;Long&gt;&gt; futures = ids.stream()<br>                // ⭐ CHANGED: Pass executor to supplyAsync()<br>                .map(id -&gt; CompletableFuture.supplyAsync(<br>                        () -&gt; callApi(id),<br>                        executor<br>                )) .toList();<br><br>      CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();<br>                /*<br>      List → loop → Array.<br>      CompletableFuture[] array = new CompletableFuture[futures.size()];<br>      <br>      for (int i = 0; i &lt; futures.size(); i++) {<br>          array[i] = futures.get(i);<br>      }<br>      CompletableFuture.allOf(array).join();<br>*/<br>        long total = futures.stream()<br>                .mapToLong(CompletableFuture::join)<br>                .sum();<br>        System.out.println(&quot;Total = &quot; + total);<br>// ⭐ NEW: Shutdown executor<br>        executor.shutdown();<br>    }<br>    private static long callApi(String id) {<br>        // API call<br>        return Long.parseLong(id) * 10;<br>    }<br>}</pre><pre>|                                    | **Without Executor** | **With Executor**  |<br>| ---------------------------------- | -------------------- | ------------------ |<br>| Code                               | Simpler              | Slightly more code |<br>| Thread pool                        | Java common pool     | Your own pool      |<br>| Control concurrency                | ❌ Limited            | ✅ Yes              |<br>| Good for HTTP calls                | ⚠️ Depends           | ✅ Recommended      |<br>| Pool size                          | Shared/global        | You decide         |<br>| Risk of affecting other async work | Higher               | Lower              |<br>| Production control                 | Lower                | Higher             |</pre><pre>List&lt;CompletableFuture&lt;Long&gt;&gt; futures = ids.stream()<br>        .map(id -&gt; webClient.get()<br>                .uri(&quot;/api/{id}&quot;, id)<br>                .retrieve()<br>                .bodyToMono(Long.class)<br>                .toFuture())<br>        .toList();</pre><h3>2. Spring Web Client</h3><p>If you’re using <strong>Spring WebClient</strong>, the usual approach is to start the 4 requests concurrently and then combine their results with Mono.zip().</p><h3>Example</h3><p>Suppose you have 4 APIs:</p><pre>Mono&lt;ResponseA&gt; api1 = webClient.get()<br>        .uri(&quot;/api1&quot;)<br>        .retrieve()<br>        .bodyToMono(ResponseA.class);<br><br>  Mono&lt;ResponseB&gt; api2 = webClient.get()<br>        .uri(&quot;/api2&quot;)<br>        .retrieve()<br>        .bodyToMono(ResponseB.class);<br>Mono&lt;ResponseC&gt; api3 = webClient.get()<br>        .uri(&quot;/api3&quot;)<br>        .retrieve()<br>        .bodyToMono(ResponseC.class);<br>Mono&lt;ResponseD&gt; api4 = webClient.get()<br>        .uri(&quot;/api4&quot;)<br>        .retrieve()<br>        .bodyToMono(ResponseD.class);</pre><p>Then execute them <strong>in parallel</strong> and aggregate the results:</p><pre>Mono&lt;AggregatedResponse&gt; result = Mono.zip(<br>        api1,<br>        api2,<br>        api3,<br>        api4<br>).map(tuple -&gt; {<br>    ResponseA a = tuple.getT1();<br>    ResponseB b = tuple.getT2();<br>    ResponseC c = tuple.getT3();<br>    ResponseD d = tuple.getT4();<br><br>return new AggregatedResponse(a, b, c, d);<br>});</pre><p>Your controller can return the Mono directly:</p><pre>@GetMapping(&quot;/aggregate&quot;)<br>public Mono&lt;AggregatedResponse&gt; aggregate() {<br><br>Mono&lt;ResponseA&gt; api1 = webClient.get()<br>            .uri(&quot;/api1&quot;)<br>            .retrieve()<br>            .bodyToMono(ResponseA.class);<br>    Mono&lt;ResponseB&gt; api2 = webClient.get()<br>            .uri(&quot;/api2&quot;)<br>            .retrieve()<br>            .bodyToMono(ResponseB.class);<br>    Mono&lt;ResponseC&gt; api3 = webClient.get()<br>            .uri(&quot;/api3&quot;)<br>            .retrieve()<br>            .bodyToMono(ResponseC.class);<br>    Mono&lt;ResponseD&gt; api4 = webClient.get()<br>            .uri(&quot;/api4&quot;)<br>            .retrieve()<br>            .bodyToMono(ResponseD.class);<br>    return Mono.zip(api1, api2, api3, api4)<br>            .map(tuple -&gt; new AggregatedResponse(<br>                    tuple.getT1(),<br>                    tuple.getT2(),<br>                    tuple.getT3(),<br>                    tuple.getT4()<br>            ));<br>}</pre><h3>Important point</h3><p>You <strong>don’t need to explicitly create 4 threads</strong>. WebClient is non-blocking, so these requests can be in-flight concurrently.</p><p>Conceptually:</p><pre>┌── API 1 ──┐<br>             │           │<br>Request ─────┼── API 2 ──┼── Mono.zip() ──&gt; AggregatedResponse<br>             │           │<br>             ├── API 3 ──┤<br>             │           │<br>             └── API 4 ──┘</pre><p>The Mono.zip() completes when <strong>all four</strong> calls have completed.</p><h3>If one API fails</h3><p>By default, if one of the four Monos errors, the combined Mono also errors.</p><p>If you want <strong>partial results</strong> — for example, API 1 fails but APIs 2–4 should still contribute — you can handle errors individually:</p><pre>Mono&lt;ResponseA&gt; api1 = webClient.get()<br>        .uri(&quot;/api1&quot;)<br>        .retrieve()<br>        .bodyToMono(ResponseA.class)<br>        .onErrorResume(e -&gt; Mono.empty());</pre><p>Or, often better, return a fallback object:</p><pre>Mono&lt;ResponseA&gt; api1 = webClient.get()<br>        .uri(&quot;/api1&quot;)<br>        .retrieve()<br>        .bodyToMono(ResponseA.class)<br>        .onErrorReturn(new ResponseA());</pre><p>If you’re doing this in a <strong>Spring Boot service layer</strong>, I can also show you the cleaner production pattern with <strong>Mono.zip + timeout + retry + individual API error handling</strong>.</p><p>=&gt;</p><p>Yes — your CompletableFuture approach is valid for <strong>dynamic requests</strong>, but there are a couple of important improvements if your actual API call is through <strong>Spring WebClient</strong>.</p><h3>Your current approach</h3><p>You dynamically create one CompletableFuture per ID:</p><pre>List&lt;String&gt; ids = List.of(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;);<br><br>List&lt;CompletableFuture&lt;Long&gt;&gt; futures = ids.stream()<br>    .map(id -&gt; CompletableFuture.supplyAsync(<br>        () -&gt; callApi(id),<br>        executor<br>    ))<br>    .toList();<br>CompletableFuture.allOf(<br>    futures.toArray(new CompletableFuture[0])<br>).join();<br>long total = futures.stream()<br>    .mapToLong(CompletableFuture::join)<br>    .sum();</pre><p>This works, but there’s an important issue:</p><p><strong>If </strong><strong>callApi() uses WebClient, you generally should not wrap it in </strong><strong>CompletableFuture.supplyAsync() just to make it parallel.</strong></p><p>WebClient is already asynchronous/non-blocking.</p><h3>Better WebClient approach for dynamic requests</h3><pre>List&lt;String&gt; ids = List.of(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;);<br><br>return Flux.fromIterable(ids)<br>    .flatMap(id -&gt;<br>        webClient.get()<br>            .uri(&quot;/api/{id}&quot;, id)<br>            .retrieve()<br>            .bodyToMono(Long.class)<br>    )<br>    .collectList();</pre><p>The return type is:</p><pre>Mono&lt;List&lt;Long&gt;&gt;</pre><p>Conceptually:</p><pre>ids<br> │<br> ├── 1 ──&gt; WebClient ──&gt; 10 ──┐<br> ├── 2 ──&gt; WebClient ──&gt; 20 ──┼──&gt; List&lt;Long&gt;<br> └── 3 ──&gt; WebClient ──&gt; 30 ──┘</pre><h3>If you want the total</h3><p>You don’t even need collectList():</p><pre>return Flux.fromIterable(ids)<br>    .flatMap(id -&gt;<br>        webClient.get()<br>            .uri(&quot;/api/{id}&quot;, id)<br>            .retrieve()<br>            .bodyToMono(Long.class)<br>    )<br>    .reduce(0L, Long::sum);</pre><p>Result:</p><pre>Mono&lt;Long&gt;</pre><p>For 1, 2, 3:</p><pre>10 + 20 + 30 = 60</pre><h3>Limit parallel requests</h3><p>This is where flatMap becomes particularly useful.</p><p>For example, you have <strong>1,000 IDs</strong>, but only want <strong>20 API calls in flight at once</strong>:</p><pre>return Flux.fromIterable(ids)<br>    .flatMap(<br>        id -&gt; webClient.get()<br>            .uri(&quot;/api/{id}&quot;, id)<br>            .retrieve()<br>            .bodyToMono(Long.class),<br>        20<br>    )<br>    .collectList();</pre><p>The 20 is the <strong>concurrency limit</strong>.</p><p>So:</p><pre>1000 IDs<br>   │<br>   ▼<br>flatMap(concurrency = 20)<br>   │<br>   ├── 20 requests<br>   │<br>   ├── as one finishes → next request<br>   │<br>   ├── as one finishes → next request<br>   │<br>   └── ...<br>   │<br>   ▼<br>List of 1000 responses</pre><h3>When your CompletableFuture approach makes sense</h3><p>If callApi(id) is a <strong>blocking</strong> API call, such as:</p><pre>private long callApi(String id) {<br>    return someBlockingHttpClient.call(id);<br>}</pre><p>then your executor approach is reasonable:</p><pre>CompletableFuture.supplyAsync(() -&gt; callApi(id), executor)</pre><p>But if:</p><pre>callApi()</pre><p>is actually:</p><pre>webClient.get()<br>    .retrieve()<br>    .bodyToMono(...)</pre><p>then prefer <strong>Flux.flatMap()</strong>.</p><p><strong>Rule of thumb:</strong></p><pre>| API style                    | Recommended                           |<br>| ---------------------------- | ------------------------------------- |<br>| WebClient / non-blocking     | `Flux.flatMap()`                      |<br>| Blocking HTTP client         | `CompletableFuture + ExecutorService` |<br>| Dynamic number of requests   | `Flux.fromIterable().flatMap()`       |<br>| Need max concurrent requests | `flatMap(..., concurrency)`           |<br>| Need all responses as a List | `.collectList()`                      |<br>| Need aggregate/sum           | `.reduce()`                           |</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02c55c94cb28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 25 Java Backend Production Scenarios Interview Questions]]></title>
            <link>https://medium.com/@nilesh.gardas/top-25-java-backend-production-scenarios-interview-questions-a1ad40f24fc6?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ad40f24fc6</guid>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 07:46:30 GMT</pubDate>
            <atom:updated>2026-08-17T08:18:39.093Z</atom:updated>
            <content:encoded><![CDATA[<p>Top 25 Java Backend Production Scenarios Interview Questions</p><p>𝗣𝗘𝗥𝗙𝗢𝗥𝗠𝗔𝗡𝗖𝗘 𝗔𝗡𝗗 𝗟𝗔𝗧𝗘𝗡𝗖𝗬:<br>1. Your API response jumps from 200 ms to 5 seconds. Where do you look first?<br>2. Fine at 100 users. Falls over at 10,000. What breaks?<br>3. CPU is normal but latency is high. What is going on?<br>4. Is the slowness in your code, the DB, the network, or a downstream call? How do you tell?<br>5. One query runs fast in dev and takes 10 seconds in prod. Why?<br>6. Memory creeps up for days, then the app crashes. Find the leak.</p><p>𝗥𝗘𝗦𝗜𝗟𝗜𝗘𝗡𝗖𝗘 𝗔𝗡𝗗 𝗙𝗔𝗜𝗟𝗨𝗥𝗘:<br>7. A downstream service is slow. How do you stop it taking down your whole app?<br>8. When do you reach for Circuit Breaker, Retry, Timeout, and Bulkhead?<br>9. Your DB connection pool is exhausted in production. Likely reasons?<br>10. Redis is down. Should your app go down with it? Design the fallback.<br>11. Cache invalidation across multiple running instances. How?</p><p>𝗜𝗗𝗘𝗠𝗣𝗢𝗧𝗘𝗡𝗖𝗬 𝗔𝗡𝗗 𝗖𝗢𝗡𝗦𝗜𝗦𝗧𝗘𝗡𝗖𝗬:<br>12. A user double clicks Pay. Retries fire. How do you stop a double charge?<br>13. Where do you store the idempotency key, and how do you handle two concurrent requests using the same one?<br>14. A network retry sends the same request twice. Same result both times. How?<br>15. A transaction that spans multiple microservices. How do you handle it?<br>16. When do you use Saga, and what happens when a compensation step itself fails?</p><p>𝗞𝗔𝗙𝗞𝗔 𝗔𝗡𝗗 𝗠𝗘𝗦𝗦𝗔𝗚𝗜𝗡𝗚:<br>17. When do you pick synchronous calls over async messaging?<br>18. A consumer processes a message, then crashes before committing the offset. Now what?<br>19. How do you stop the same Kafka event being processed twice?</p><p>𝗞𝗨𝗕𝗘𝗥𝗡𝗘𝗧𝗘𝗦 𝗔𝗡𝗗 𝗗𝗘𝗣𝗟𝗢𝗬𝗠𝗘𝗡𝗧:<br>20. Your pod keeps restarting but the logs show nothing. Debug it.<br>21. Ship a new version of a Spring Boot service with zero downtime. How?<br>22. A pod is terminating. What happens to in-flight requests, and how do you shut down cleanly?</p><p>𝗦𝗖𝗔𝗟𝗘 𝗔𝗡𝗗 𝗗𝗔𝗧𝗔:<br>23. Rate limiting for an API hit by millions of users. Design it.<br>24. Process a 5 GB CSV without an OutOfMemoryError. How?<br>25. A bug only fires under heavy traffic, never locally. How do you catch it?</p><p>1. How to make external API call from service class.<br>2. Making a call to 4 external API, how can I aggregate the response into one .<br>3. How to mitigate the issue when one of the four services is down.<br>4. What happens when we don’t use stereotypes annotations in our spring boot application.<br>5. How can we customise auto configurations in Spring Boot application.<br>6. What is asynchronous and synchronous communication, when to use one .<br>7. ForkJoinPool vs Executor service.<br>8. Arraylist vs LinkedList.<br>9. Why will we use parallel streams over normal .<br>10. Spring boot application flow/architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ad40f24fc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Theory]]></title>
            <link>https://medium.com/@nilesh.gardas/docker-theory-27cb1e7e5fe1?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/27cb1e7e5fe1</guid>
            <category><![CDATA[dockerfile-basic]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfile-example]]></category>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 16:21:43 GMT</pubDate>
            <atom:updated>2026-08-16T16:21:43.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*3c7MkE-1-dnvhWRo0eRsYg.png" /></figure><p>Docker is an open-source platform that lets you <strong>package, distribute, and run applications in isolated environments called containers</strong>. It helps ensure that an application works the same way on a developer’s laptop, a test server, or in production.</p><p>With Docker, you package everything your app needs into a <strong>Docker image</strong>, and anyone with Docker installed can run it consistently.</p><h3>Key Concepts</h3><ul><li><strong>Image</strong>: A blueprint for your application, including the code, runtime, libraries, and dependencies.</li><li><strong>Container</strong>: A running instance of an image. You can start, stop, and delete containers.</li><li><strong>Dockerfile</strong>: A text file containing instructions for building a Docker image.</li><li><strong>Docker Hub</strong>: An online repository where you can share and download Docker images.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kk2QEykzOGdx8MdMkGrtvA.png" /></figure><h4>1. Why Docker Exists &amp; VMs vs. Containers [<a href="https://www.youtube.com/watch?v=N0EUVY6EPcA&amp;t=78">01:18</a>]</h4><ul><li><strong>The Problem:</strong> Software often works on a developer’s machine but breaks in testing or production due to OS differences, dependencies, and configuration drift.</li><li><strong>VMs vs. Containers:</strong></li><li><strong>Virtual Machines (VMs):</strong> Heavy and slow because each VM carries a complete Guest Operating System on top of a hypervisor.</li><li><strong>Containers:</strong> Lightweight and fast because they share the host system’s Linux kernel (isolation happens at the process level, not the hardware level).</li></ul><h4>2. Architecture &amp; Components [<a href="https://www.youtube.com/watch?v=N0EUVY6EPcA&amp;t=220">03:40</a>]</h4><ul><li><strong>Docker Client (CLI):</strong> The command-line tool used to send commands.</li><li><strong>Docker Daemon (Engine):</strong> The background service that builds images, runs containers, and manages networks/volumes.</li><li><strong>Docker Hub:</strong> A central registry service (like GitHub for container images) to pull/push images (e.g., Nginx, MySQL).</li><li><strong>Docker Desktop:</strong> Runs a lightweight Linux VM under the hood on macOS and Windows so the Docker Daemon can execute Linux-native containers seamlessly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*-GTRZoCy8fFMtE5a" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*xjwPnGYtXj-AouuX" /></figure><h4>3. Dockerfile, Image &amp; Container Relationship [<a href="https://www.youtube.com/watch?v=N0EUVY6EPcA&amp;t=371">06:11</a>]</h4><ul><li><strong>Dockerfile:</strong> A text file containing build instructions (e.g., FROM, WORKDIR, COPY, EXPOSE, CMD, ENTRYPOINT).</li><li><strong>Docker Image:</strong> A static, read-only blueprint created by docker build.</li><li><strong>Docker Container:</strong> A running, isolated instance of an image spawned via docker run.</li></ul><blockquote><strong><em>CMD vs. ENTRYPOINT [</em></strong><a href="https://www.youtube.com/watch?v=N0EUVY6EPcA&amp;t=474"><strong><em>07:54</em></strong></a><strong><em>]:</em></strong></blockquote><ul><li>CMD sets flexible default commands that can be overridden at runtime.</li><li>ENTRYPOINT locks the container into executing a specific binary.</li></ul><h4>4. Image Layers &amp; Caching [<a href="https://www.youtube.com/watch?v=N0EUVY6EPcA&amp;t=504">08:24</a>]</h4><ul><li>Each instruction in a Dockerfile creates a read-only layer.</li><li><strong>Caching:</strong> Re-building reuses unchanged layers. Place rarely changed dependencies early in the Dockerfile and frequently changing app code toward the bottom to speed up builds.</li></ul><h4>5. Container Lifecycle &amp; Data Storage [<a href="https://www.youtube.com/watch?v=N0EUVY6EPcA&amp;t=583">09:43</a>]</h4><ul><li><strong>Lifecycle:</strong> Created $\rightarrow$ Running $\rightarrow$ Paused/Stopped $\rightarrow$ Removed. Stopping preserves data, but removing a container deletes its writable layer.</li><li><strong>Data Persistence:</strong></li><li><strong>Volumes:</strong> Managed by Docker (/var/lib/docker/volumes), platform-independent, best for <strong>production</strong>.</li><li><strong>Bind Mounts:</strong> Maps a local host directory into the container, allowing live-code updates, best for <strong>development</strong>.</li></ul><h4>6. Networking &amp; Docker Compose [<a href="https://www.youtube.com/watch?v=N0EUVY6EPcA&amp;t=705">11:45</a>]</h4><ul><li><strong>Networking Types:</strong></li><li><strong>Bridge (Default):</strong> Connects containers on a single host.</li><li><strong>Host:</strong> Shares the host network directly for maximum speed.</li><li><strong>None:</strong> Complete network isolation.</li><li><strong>Overlay:</strong> Connects containers across multiple Docker hosts (Docker Swarm/Kubernetes foundation).</li><li><strong>Docker Compose [</strong><a href="https://www.youtube.com/watch?v=N0EUVY6EPcA&amp;t=792"><strong>13:12</strong></a><strong>]:</strong> Uses a docker-compose.yml file to define and manage multi-container setups (e.g., App + Database + Cache) with simple commands:</li><li><strong>Dockerfile Directives:</strong></li><li>FROM: Base image.</li><li>WORKDIR: Internal directory path.</li><li>COPY: Host file $\rightarrow$ Container path.</li><li>CMD vs ENTRYPOINT: CMD sets default arguments (easily overridden), whereas ENTRYPOINT locks the execution binary.</li><li><strong>Data Persistence:</strong></li><li><strong>Volumes:</strong> Docker-managed path (/var/lib/docker/volumes), platform-independent $\rightarrow$ <strong>Production</strong>.</li><li><strong>Bind Mounts:</strong> Maps directly to a path on the host machine $\rightarrow$ <strong>Development / Hot Reloading</strong>.</li><li><strong>Orchestration:</strong> Use <strong>Docker Compose</strong> (docker-compose.yml) to define and run multi-container applications with single commands like docker compose up -d and docker compose down.</li></ul><h3>How Docker Works</h3><pre>Application Code<br>        │<br>        ▼<br>   Dockerfile<br>        │<br>        ▼<br>  Docker Image<br>        │<br>        ▼<br> Docker Container</pre><h3>Example</h3><p>Suppose you have a simple Python app:</p><pre>print(&quot;Hello, Docker!&quot;)</pre><p>A simple <strong>Dockerfile </strong>might look like:</p><pre>FROM python:3.12<br><br>WORKDIR /app<br><br>COPY . .<br><br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>Build the image:</p><pre>docker build -t hello-docker .</pre><p>Run the container:</p><pre>docker run hello-docker</pre><p>Output:</p><pre>Hello, Docker!</pre><h3>Common Docker Commands</h3><pre>docker --version          # Check Docker version<br>docker pull nginx         # Download an image<br>docker images             # List images<br>docker ps                 # List running containers<br>docker run nginx          # Run a container<br>docker stop &lt;container&gt;   # Stop a container<br>docker rm &lt;container&gt;     # Remove a container<br>docker rmi &lt;image&gt;        # Remove an image</pre><h3>Real-world Uses</h3><ul><li>Developing applications consistently across different machines.</li><li>Deploying applications to cloud platforms.</li><li>Running databases like MySQL, PostgreSQL, or MongoDB in containers.</li><li>Building microservices architectures.</li><li>Automating testing and deployment (CI/CD).</li></ul><p>In short, <strong>Docker packages an application and all of its dependencies into a portable container</strong>, making it easy to run the application reliably in any environment where Docker is installed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27cb1e7e5fe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<AWS> AWS Region vs Availability Zone]]></title>
            <link>https://medium.com/@nilesh.gardas/aws-aws-region-vs-availability-zone-30d42d074f79?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d42d074f79</guid>
            <category><![CDATA[aws-availability-zones]]></category>
            <category><![CDATA[aws-region]]></category>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 07:25:50 GMT</pubDate>
            <atom:updated>2026-08-15T07:25:50.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOgJBcyMFkc37prMk2zR5w.png" /></figure><p>In AWS, a <strong>Region</strong> is a large geographic area, while an <strong>Availability Zone (AZ)</strong> is an isolated data center (or group of data centers) within a Region.</p><p><strong>Region = where your application is geographically located.</strong><br> <strong>AZ = separate infrastructure within that Region that protects against failures.</strong></p><p>Here’s a simple way to think about it:</p><blockquote><strong><em>Region = City</em></strong><em><br> </em><strong><em>Availability Zone = Building in that city</em></strong></blockquote><ul><li>A <strong>Region</strong> is a <strong>geographic location</strong> containing multiple Availability Zones.</li><li>An <strong>Availability Zone</strong> is an <strong>isolated data center (or group of data centers)</strong> within a Region, designed to provide resilience and high availability.</li></ul><pre>AWS Global Infrastructure<br>│<br>├── Region: us-east-1 (Northern Virginia)<br>│   ├── AZ: us-east-1a<br>│   ├── AZ: us-east-1b<br>│   └── AZ: us-east-1c<br>│<br>├── Region: eu-west-1 (Ireland)<br>│   ├── AZ: eu-west-1a<br>│   ├── AZ: eu-west-1b<br>│   └── AZ: eu-west-1c</pre><h4>Inside us-east Region, AWS might have multiple AZs:</h4><ul><li>us-east-1a</li><li>us-east-1b</li><li>us-east-1c</li><li>us-east-1d</li></ul><p>Each AZ has independent:</p><ul><li>Power</li><li>Cooling</li><li>Networking</li></ul><p>This means if one AZ experiences an outage, applications running in another AZ within the same Region can continue operating.</p><h3>Why use multiple Availability Zones?</h3><p>For high availability.</p><ul><li>Disaster recovery</li><li>Lower latency for global users</li><li>Compliance and data residency requirements</li></ul><p>For example:</p><ul><li><strong>EC2 Instance 1</strong> → us-east-1a</li><li><strong>EC2 Instance 2</strong> → us-east-1b</li><li><strong>Load Balancer</strong> distributes traffic between them</li></ul><p>If us-east-1a fails, traffic is automatically routed to the instance in us-east-1b.</p><h3>Why use multiple Regions?</h3><p>For:</p><ul><li>Disaster recovery</li><li>Lower latency for global users</li><li>Compliance and data residency requirements</li></ul><h4>Imagine you run your application on servers in just <strong>one data center</strong>. If that data center has:</h4><ul><li>Power failure ⚡</li><li>Network failure 🌐</li><li>Hardware problems</li><li>Fire or other physical disaster</li></ul><p>your application could go down.</p><p>AWS solves this by putting multiple <strong>isolated Availability Zones</strong> inside a Region.</p><h3>In one sentence</h3><blockquote><strong><em>The purpose of an Availability Zone is to isolate infrastructure failures and allow you to run applications across multiple locations for higher availability and reliability.</em></strong></blockquote><p><strong>Region = where your application is geographically located.</strong><br> <strong>AZ = separate infrastructure within that Region that protects against failures.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d42d074f79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<AWS> Amazon ECR]]></title>
            <link>https://medium.com/@nilesh.gardas/aws-amazon-ecr-d0c7762bc29b?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0c7762bc29b</guid>
            <category><![CDATA[aws-ecr]]></category>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 18:02:29 GMT</pubDate>
            <atom:updated>2026-08-13T18:02:29.688Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Amazon Elastic Container Registry (Amazon ECR)</strong> is a fully managed Docker and OCI container image registry service provided by AWS. It allows you to securely store, manage, and distribute container images without operating your own registry. It integrates natively with AWS container services such as Amazon ECS and Amazon EKS. (<a href="https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html?utm_source=chatgpt.com">AWS Documentation</a>)</p><blockquote><strong>OCI</strong> stands for <strong>Open Container Initiative</strong>. It defines open standards so container images can work consistently across different container tools and platforms.</blockquote><blockquote>OCI provides common standards for:</blockquote><blockquote><strong>Image format → Runtime → Distribution</strong></blockquote><blockquote>So an image built using one compatible tool can be stored in a registry and run by another compatible container runtime.</blockquote><h4>Common use cases</h4><blockquote>Storing Docker images for <strong>Amazon ECS</strong>.</blockquote><blockquote>Hosting images for <strong>Amazon EKS</strong> (Kubernetes).</blockquote><blockquote>Managing images in CI/CD pipelines (GitHub Actions, Jenkins, CodePipeline).</blockquote><blockquote>Secure private container registries for enterprise applications.</blockquote><h3>Key features</h3><ul><li><strong>Private and public repositories</strong> for storing container images.</li><li><strong>Image vulnerability scanning</strong> to identify known security issues.</li><li><strong>IAM-based access control</strong> for fine-grained permissions.</li><li><strong>Lifecycle policies</strong> to automatically delete old or unused images.</li><li><strong>Cross-account and cross-region replication</strong> for high availability.</li><li><strong>Image signing</strong> to verify image authenticity.</li><li><strong>Pull-through cache</strong> to cache images from external registries like Docker Hub. (<a href="https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html?utm_source=chatgpt.com">AWS Documentation</a>)</li></ul><h3>Typical workflow</h3><ol><li>Build a Docker image.</li><li>Create an ECR repository.</li><li>Authenticate Docker with ECR.</li><li>Push the image to ECR.</li><li>Deploy the image from ECR to ECS, EKS, AWS Lambda (container images), or other Kubernetes environments.</li></ol><h3>Example commands</h3><p>Create a repository:</p><pre>aws ecr create-repository --repository-name my-app</pre><p>Authenticate Docker:</p><pre>aws ecr get-login-password --region us-east-1 | \<br>docker login --username AWS --password-stdin \<br>&lt;account-id&gt;.dkr.ecr.us-east-1.amazonaws.com</pre><p>Build the image:</p><pre>docker build -t my-app .</pre><p>Tag the image:</p><pre>docker tag my-app:latest \<br>&lt;account-id&gt;.dkr.ecr.us-east-1.amazonaws.com/my-app:latest</pre><p>Push the image:</p><pre>docker push &lt;account-id&gt;.dkr.ecr.us-east-1.amazonaws.com/my-app:latest</pre><h3>Amazon ECR vs Docker Hub</h3><pre>| Amazon ECR                        | Docker Hub                  |<br>| --------------------------------- | --------------------------- |<br>| AWS-managed registry              | Public/private registry     |<br>| Integrated with IAM               | Uses Docker accounts        |<br>| Native ECS/EKS integration        | General-purpose registry    |<br>| Image scanning and replication    | Available depending on plan |<br>| Pay for storage and data transfer | Free and paid tiers         |</pre><h3>Common use cases</h3><ul><li>Storing Docker images for <strong>Amazon ECS</strong>.</li><li>Hosting images for <strong>Amazon EKS</strong> (Kubernetes).</li><li>Managing images in CI/CD pipelines (GitHub Actions, Jenkins, CodePipeline).</li><li>Secure private container registries for enterprise applications.</li></ul><p>For more details, see the official documentation: <a href="https://docs.aws.amazon.com/ecr/?utm_source=chatgpt.com">Amazon ECR Documentation</a> and the service overview: <a href="https://aws.amazon.com/ecr/?sec=srv&amp;utm_source=chatgpt.com">Amazon ECR Overview</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0c7762bc29b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<AWS> What is EKS ?]]></title>
            <link>https://medium.com/@nilesh.gardas/aws-what-is-eks-7d09bf0edd6d?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d09bf0edd6d</guid>
            <category><![CDATA[amazon-eks]]></category>
            <category><![CDATA[aws-eks]]></category>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 18:01:58 GMT</pubDate>
            <atom:updated>2026-08-13T18:01:58.476Z</atom:updated>
            <content:encoded><![CDATA[<h4>AWS EKS is a Managed Kubernetes Service called Elastic Kubernetes Service by Amazon.</h4><p>Amazon EKS (Elastic Kubernetes Service) is a managed Kubernetes service from AWS. It allows us to run Kubernetes on AWS while<strong> AWS manages the Kubernetes control plane</strong>. <strong>We are responsible for the worker nodes and our applications running on them</strong>. Tools like eksctl make it easier to create and manage EKS clusters.</p><h4>AWS EKS is actually provides services as:</h4><blockquote>Its Managed Kubernetes <strong>cluster/service</strong></blockquote><blockquote><strong>EKS helps in running the Kubernetes cluster on AWS, taking care of the Master Nodes.</strong></blockquote><blockquote><strong>All the necessary applications/services, like the container runtime or master processes are already pre-installed.</strong></blockquote><blockquote><strong>And in addition to that it also takes care of scaling and backups.</strong></blockquote><blockquote><strong>So, you only create and care about the Worker Nodes.</strong></blockquote><h3>In simple words</h3><blockquote><strong>EKS</strong> stands for <strong>Elastic Kubernetes Service</strong>.</blockquote><blockquote>It is a <strong>managed Kubernetes service from AWS</strong>.</blockquote><blockquote>EKS lets you run a <strong>Kubernetes cluster on AWS</strong>.</blockquote><blockquote><strong>AWS takes care of the Master/Control Plane nodes</strong>.</blockquote><blockquote>The required Kubernetes components are already set up by AWS.</blockquote><blockquote>AWS also handles things like <strong>scaling and backups</strong> for the managed control plane.</blockquote><blockquote><strong>You mainly create and manage the Worker Nodes</strong>, where your applications actually run.</blockquote><h4>We as Developer in AWS EKS:</h4><blockquote><strong>So, you only create and care about the Worker Nodes.</strong></blockquote><blockquote>EKS helps a developer mainly by <strong>running your application containers reliably without you having to manage the Kubernetes control plane yourself</strong>.</blockquote><pre>| Term              | Meaning                                            |<br>| ----------------- | -------------------------------------------------- |<br>| **EKS**           | Managed Kubernetes service from AWS                |<br>| **Control Plane** | Manages the Kubernetes cluster                     |<br>| **Worker Node**   | Machine that runs Pods/applications                |<br>| **EC2**           | AWS virtual machines commonly used as worker nodes |<br>| **Node Group**    | Group of worker nodes                              |<br>| **eksctl**        | CLI tool that simplifies EKS cluster creation      |</pre><p>Think of it this way:</p><p><strong>Without EKS:</strong></p><pre>Your code<br>   ↓<br>You manage servers<br>   ↓<br>Install/configure Docker/Kubernetes<br>   ↓<br>Deploy application<br>   ↓<br>Handle scaling, failures, etc.</pre><p><strong>With EKS:</strong></p><pre>Your code<br>   ↓<br>Docker image<br>   ↓<br>ECR<br>   ↓<br>EKS<br>   ↓<br>Your application runs as Pods</pre><h3>Where EKS helps you as a developer</h3><p><strong>1. Easy deployment</strong></p><p>You package your application as a container and deploy it to EKS.</p><pre>kubectl apply -f deployment.yaml</pre><p>EKS/Kubernetes takes care of getting the desired number of Pods running.</p><p><strong>2. Automatic recovery</strong></p><p>Suppose you need 3 application Pods:</p><pre>Pod 1  ✅<br>Pod 2  ❌<br>Pod 3  ✅</pre><p>Kubernetes notices that only 2 are running and creates another Pod.</p><pre>Pod 1  ✅<br>Pod 2  ❌ → replaced<br>Pod 3  ✅<br>Pod 4  ✅</pre><p>You don’t have to manually restart the application.</p><p><strong>3. Scaling</strong></p><p>If your application gets more traffic:</p><pre>Normal traffic<br>     ↓<br>3 Pods</pre><p>During high traffic:</p><pre>High traffic<br>     ↓<br>3 → 6 → 10 Pods</pre><p>You can use <strong>Horizontal Pod Autoscaling (HPA)</strong>.</p><p><strong>4. Load balancing</strong></p><p>You might have multiple copies of your application:</p><pre>Users<br>                ↓<br>          Load Balancer<br>                ↓<br>       ┌────────┼────────┐<br>       ↓        ↓        ↓<br>     Pod 1    Pod 2    Pod 3</pre><p>Requests are distributed across your application instances.</p><p><strong>5. Zero/minimal-downtime deployments</strong></p><p>Suppose you’re deploying version 2:</p><pre>v1: Pod 1  Pod 2  Pod 3<br>             ↓<br>          Deployment<br>             ↓<br>v2: Pod 4  Pod 5  Pod 6</pre><p>Kubernetes can gradually replace v1 with v2 rather than taking the whole application down.</p><p><strong>6. Standard way to deploy different applications</strong></p><p>If you have:</p><pre>Java API<br>Node.js API<br>Python service<br>Background worker</pre><p>they can all run as containers in the same EKS environment, with Kubernetes managing them consistently.</p><h4>The key point</h4><p>As a developer, <strong>EKS is not primarily something you use to write code</strong>.</p><p>It’s the <strong>platform where your containerized code runs</strong>.</p><h3>Q. what is Kubernetes cluster ?</h3><ul><li>&gt;</li></ul><p>A <strong>Kubernetes cluster</strong> is a group of machines (physical or virtual) that work together to run and manage containerized applications. Kubernetes automates deployment, scaling, networking, and recovery of these applications.</p><p><strong>A Kubernetes cluster consists of:</strong></p><ul><li><strong>Control Plane</strong>: Manages and coordinates the cluster.</li><li><strong>Worker Nodes</strong>: Run your applications.</li><li><strong>Pods</strong>: Contain the application containers.</li></ul><p>Together, these components provide a reliable platform for running containerized applications at scale.</p><h3>Components of a Kubernetes cluster</h3><pre>Kubernetes Cluster<br>      +----------------------------------+<br>      |                                  |<br>      |  Control Plane (Master Node)     |<br>      |  - API Server                    |<br>      |  - Scheduler                     |<br>      |  - Controller Manager            |<br>      |  - etcd (cluster database)       |<br>      |                                  |<br>      |----------------------------------|<br>      |  Worker Node 1                   |<br>      |  - Kubelet                       |<br>      |  - Container Runtime             |<br>      |  - Pods                          |<br>      |                                  |<br>      |----------------------------------|<br>      |  Worker Node 2                   |<br>      |  - Kubelet                       |<br>      |  - Container Runtime             |<br>      |  - Pods                          |<br>      +----------------------------------+</pre><h3>Main parts</h3><h4>1. Control Plane</h4><p>The control plane manages the entire cluster. It:</p><ul><li>Receives deployment requests.</li><li>Decides where applications should run.</li><li>Monitors the cluster’s health.</li><li>Restarts failed applications.</li></ul><p>Key components:</p><ul><li><strong>API Server</strong> — Entry point for all Kubernetes commands.</li><li><strong>Scheduler</strong> — Assigns Pods to worker nodes.</li><li><strong>Controller Manager</strong> — Keeps the desired state of the cluster.</li><li><strong>etcd</strong> — Stores cluster configuration and state.</li></ul><h4>2. Worker Nodes</h4><p>Worker nodes are the machines where your applications actually run.</p><p>Each worker node contains:</p><ul><li><strong>Kubelet</strong> — Communicates with the control plane.</li><li><strong>Container Runtime</strong> — Runs containers (such as containerd).</li><li><strong>Pods</strong> — The smallest deployable unit in Kubernetes.</li></ul><h3>What is a Pod?</h3><p>A <strong>Pod</strong> is one or more containers that are deployed together and share networking and storage.</p><p>Example:</p><pre>Pod<br>+----------------------+<br>| Nginx Container      |<br>| Logging Container    |<br>+----------------------+</pre><h3>How a deployment works</h3><ol><li>You create a Deployment.</li><li>The API Server receives it.</li><li>The Scheduler selects a worker node.</li><li>The Kubelet on that node starts the Pod.</li><li>If the Pod crashes, Kubernetes automatically creates a replacement.</li></ol><h3>Example</h3><p>Suppose you deploy a web application with <strong>3 replicas</strong>.</p><pre>Control Plane<br>      |<br>      | Schedules Pods<br>      |<br>+-------------+    +-------------+<br>| Worker 1    |    | Worker 2    |<br>|-------------|    |-------------|<br>| Pod (Web)   |    | Pod (Web)   |<br>| Pod (Web)   |    |             |<br>+-------------+    +-------------+</pre><p>If <strong>Worker 1</strong> fails:</p><pre>Before Failure:<br>Worker 1 -&gt; Pod1, Pod2<br>Worker 2 -&gt; Pod3</pre><pre>After Failure:<br>Worker 1 -&gt; Down<br>Worker 2 -&gt; Pod3, Pod4, Pod5</pre><p>Kubernetes automatically creates new Pods on healthy nodes to maintain the desired number of replicas.</p><h3>Benefits of a Kubernetes cluster</h3><ul><li><strong>High availability</strong> — Applications continue running even if a node fails.</li><li><strong>Automatic scaling</strong> — Increase or decrease the number of Pods based on demand.</li><li><strong>Self-healing</strong> — Restarts or replaces failed Pods automatically.</li><li><strong>Load balancing</strong> — Distributes traffic across application instances.</li><li><strong>Rolling updates</strong> — Deploy new versions with little or no downtime.</li><li><strong>Efficient resource usage</strong> — Schedules workloads across available machines.</li></ul><h3>What a developer typically does in EKS</h3><ol><li><strong>Containerize the application</strong></li></ol><ul><li>Create a Dockerfile</li><li>Build the Docker image</li><li>Push the image to <strong>Amazon ECR</strong></li></ul><ol><li><strong>Create Kubernetes deployment files</strong><br> Developers commonly work with:</li></ol><ul><li>Deployment — how many application pods should run</li><li>Service — how other applications/users reach the pods</li><li>ConfigMap — non-sensitive configuration</li><li>Secret — sensitive configuration</li><li>Ingress — external HTTP/HTTPS access</li><li>HPA — automatic scaling based on CPU/memory/custom metrics</li></ul><ol><li><strong>Deploy to EKS</strong><br> Typical workflow:</li></ol><pre>Developer<br>   ↓<br>Code<br>   ↓<br>Docker Image<br>   ↓<br>Amazon ECR<br>   ↓<br>Kubernetes YAML / Helm<br>   ↓<br>EKS<br>   ↓<br>Pods → Service → Users</pre><ol><li><strong>Use Kubernetes commands</strong><br> Developers should generally be comfortable with:</li></ol><pre>kubectl get pods<br>kubectl get deployments<br>kubectl get services<br>kubectl describe pod &lt;pod&gt;<br>kubectl logs &lt;pod&gt;<br>kubectl apply -f deployment.yaml<br>kubectl rollout status deployment/my-app<br>kubectl rollout restart deployment/my-app</pre><ol><li><strong>Configure application scaling</strong><br> For example, you might configure an HPA so that:</li></ol><pre>CPU &gt; 70%<br>    ↓<br>Kubernetes increases pods<br>    ↓<br>CPU decreases<br>    ↓<br>Kubernetes reduces pods</pre><ol><li><strong>Handle application-level troubleshooting</strong><br> If a pod isn’t working, developers investigate things such as:</li></ol><ul><li>Application logs</li><li>Environment variables</li><li>Container image</li><li>Ports</li><li>Health/readiness probes</li><li>Resource requests/limits</li><li>Kubernetes events</li><li>Application connectivity</li></ul><h3>What developers usually DON’T manage</h3><p>Depending on the organization’s setup, the platform/DevOps team may handle:</p><ul><li>Creating the EKS cluster</li><li>VPC/subnets</li><li>Node groups / EC2 infrastructure</li><li>IAM infrastructure</li><li>Load balancer infrastructure</li><li>Cluster upgrades</li><li>Networking</li><li>Security policies</li><li>Monitoring infrastructure</li><li>Terraform/CloudFormation for the platform</li></ul><pre>| Area                   | Developer | DevOps/Platform |<br>| ---------------------- | --------- | --------------- |<br>| Application code       | ✅         |                 |<br>| Dockerfile             | ✅         |                 |<br>| ECR image              | ✅         | Shared          |<br>| Kubernetes YAML/Helm   | ✅         | Shared          |<br>| Deploy application     | ✅         | Shared          |<br>| Debug pods/logs        | ✅         | Shared          |<br>| EKS cluster creation   |           | ✅               |<br>| VPC/networking         |           | ✅               |<br>| Node groups            |           | ✅               |<br>| IAM architecture       |           | ✅               |<br>| Cluster upgrades       |           | ✅               |<br>| CI/CD pipeline         | Shared    | ✅               |<br>| Application monitoring | ✅         | Shared          |</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xYxl4w0fvVkVBcTyUrqYUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4Uh_2oFX8xGtHtRTNrpFaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ZYM3p2wyqFTeCS5A5hWzWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xra-cz5syTrSAJIM0sdNtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*gxjSPE0f8jIQShjVbhU6wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*BpUMcSEX4QRKppP_mCib7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*_R2IfEJDdNPhXqmcKB2D-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*RIdOcFfo6eZWViVQ3qLfMQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d09bf0edd6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<React> Pagination and infinite scroll use asynchronous API calls from React]]></title>
            <link>https://medium.com/@nilesh.gardas/react-pagination-and-infinite-scroll-use-asynchronous-api-calls-from-react-2c64c99aa705?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c64c99aa705</guid>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 07:01:31 GMT</pubDate>
            <atom:updated>2026-08-04T07:01:31.967Z</atom:updated>
            <content:encoded><![CDATA[<p>From a React application, <strong>both pagination and infinite scroll API calls are asynchronous</strong>. That’s the standard approach because HTTP requests are asynchronous in JavaScript.</p><h4>Pagination</h4><p>When the user clicks “Next” or a page number, React makes an async request:</p><pre>const fetchPage = async (page) =&gt; {<br>  const response = await fetch(`/api/products?page=${page}&amp;size=20`);<br>  const data = await response.json();<br>  setProducts(data.content);<br>};</pre><p>Flow:</p><ol><li>User clicks “Next”.</li><li>Async API request is sent.</li><li>UI can show a loading spinner.</li><li>Response arrives.</li><li>State is updated and the new page is rendered.</li></ol><h4>Infinite Scroll</h4><p>It’s also asynchronous. The difference is <strong>when</strong> the request is triggered.</p><pre>const loadMore = async () =&gt; {<br>  const response = await fetch(`/api/products?page=${page}&amp;size=20`);<br>  const data = await response.json();<br><br>  setProducts(prev =&gt; [...prev, ...data.content]);<br>  setPage(prev =&gt; prev + 1);<br>};</pre><p>Flow:</p><ol><li>User scrolls near the bottom.</li><li>Async API request is sent.</li><li>Loading indicator appears (optional).</li><li>Response arrives.</li><li>New items are appended to the existing list.</li></ol><h3>Are they synchronous?</h3><p>No. A synchronous HTTP request would block the browser until it completed, which would freeze the UI. Modern React applications use asynchronous requests (via fetch, axios, React Query, SWR, etc.).</p><h3>One important difference</h3><p>Although the requests are asynchronous, you usually <strong>prevent multiple simultaneous requests</strong> in infinite scroll.</p><p>For example:</p><pre>const [loading, setLoading] = useState(false);<br><br>const loadMore = async () =&gt; {<br>  if (loading) return;<br>  setLoading(true);<br>  try {<br>    const response = await fetch(`/api/products?page=${page}`);<br>    const data = await response.json();<br>    setProducts(prev =&gt; [...prev, ...data.content]);<br>    setPage(prev =&gt; prev + 1);<br>  } finally {<br>    setLoading(false);<br>  }<br>};</pre><p>This avoids sending duplicate requests if the user scrolls quickly while a previous request is still in progress.</p><p>So, <strong>both pagination and infinite scroll use asynchronous API calls</strong>, with the key difference being the trigger (button/page change versus scroll event) and the way the returned data is displayed (replace versus append).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c64c99aa705" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[<React> Implement react-infinite-scroll-component react]]></title>
            <link>https://medium.com/@nilesh.gardas/react-implement-react-infinite-scroll-component-react-778c061d1b7a?source=rss-caa0fda9090d------2</link>
            <guid isPermaLink="false">https://medium.com/p/778c061d1b7a</guid>
            <dc:creator><![CDATA[Nilesh Gardas]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 06:57:34 GMT</pubDate>
            <atom:updated>2026-08-04T06:57:34.923Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>install the package first:</strong></li></ol><pre>npm install react-infinite-scroll-component<br><br>#use like below :<br><br>import InfiniteScroll from &#39;./components/InfiniteScroll&#39;;</pre><p>For react-infinite-scroll-component, the API usually follows a <strong>pagination pattern</strong>. The frontend sends the current page (or cursor), and the backend returns the next batch of items plus information about whether more data exists.</p><h4>Example: Page-based pagination</h4><h4>1. API Request</h4><p>When the page loads:</p><pre>GET /api/products?page=1&amp;limit=10</pre><p>After scrolling:</p><pre>GET /api/products?page=2&amp;limit=10</pre><h4>2. API Response</h4><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;id&quot;: 1,<br>      &quot;title&quot;: &quot;iPhone 15&quot;,<br>      &quot;price&quot;: 79999<br>    },<br>    {<br>      &quot;id&quot;: 2,<br>      &quot;title&quot;: &quot;Samsung Galaxy S24&quot;,<br>      &quot;price&quot;: 69999<br>    }<br>  ],<br>  &quot;pagination&quot;: {<br>    &quot;currentPage&quot;: 1,<br>    &quot;pageSize&quot;: 10,<br>    &quot;totalItems&quot;: 100,<br>    &quot;totalPages&quot;: 10,<br>    &quot;hasNextPage&quot;: true<br>  }<br>}</pre><p>The React component uses:</p><ul><li>data → append these items to the existing list</li><li>hasNextPage → set hasMore</li><li>currentPage → request the next page</li></ul><h4>React + TypeScript example with this API</h4><pre>import React, { useCallback, useEffect, useState } from &quot;react&quot;;<br>import InfiniteScroll from &quot;react-infinite-scroll-component&quot;;<br><br>interface Product {<br>  id: number;<br>  title: string;<br>  price: number;<br>}<br><br>interface ProductResponse {<br>  data: Product[];<br>  pagination: {<br>    currentPage: number;<br>    pageSize: number;<br>    totalItems: number;<br>    totalPages: number;<br>    hasNextPage: boolean;<br>  };<br>}<br><br>const ProductList: React.FC = () =&gt; {<br>  const [products, setProducts] = useState&lt;Product[]&gt;([]);<br>  const [page, setPage] = useState(1);<br>  const [hasMore, setHasMore] = useState(true);<br>  const [loading, setLoading] = useState(false);<br><br>  const fetchProducts = useCallback(async () =&gt; {<br>    if (loading || !hasMore) return;<br><br>    try {<br>      setLoading(true);<br><br>      const response = await fetch(<br>        `/api/products?page=${page}&amp;limit=10`<br>      );<br><br>      const result: ProductResponse = await response.json();<br><br>      setProducts((prev) =&gt; [<br>        ...prev,<br>        ...result.data,<br>      ]);<br><br>      setHasMore(result.pagination.hasNextPage);<br><br>      setPage((prev) =&gt; prev + 1);<br>    } catch (error) {<br>      console.error(&quot;Failed to fetch products&quot;, error);<br>    } finally {<br>      setLoading(false);<br>    }<br>  }, [page, loading, hasMore]);<br><br>  useEffect(() =&gt; {<br>    fetchProducts();<br>  }, []);<br><br>  return (<br>    &lt;div<br>      id=&quot;product-scroll-container&quot;<br>      style={{<br>        height: &quot;600px&quot;,<br>        overflow: &quot;auto&quot;,<br>        padding: &quot;20px&quot;,<br>      }}<br>    &gt;<br>      &lt;InfiniteScroll<br>        dataLength={products.length}<br>        next={fetchProducts}<br>        hasMore={hasMore}<br>        loader={<br>          &lt;p style={{ textAlign: &quot;center&quot; }}&gt;<br>            Loading products...<br>          &lt;/p&gt;<br>        }<br>        endMessage={<br>          &lt;p style={{ textAlign: &quot;center&quot; }}&gt;<br>            &lt;b&gt;No more products&lt;/b&gt;<br>          &lt;/p&gt;<br>        }<br>        scrollableTarget=&quot;product-scroll-container&quot;<br>      &gt;<br>        {products.map((product) =&gt; (<br>          &lt;div<br>            key={product.id}<br>            style={{<br>              border: &quot;1px solid #ddd&quot;,<br>              padding: &quot;15px&quot;,<br>              marginBottom: &quot;10px&quot;,<br>              borderRadius: &quot;8px&quot;,<br>            }}<br>          &gt;<br>            &lt;h3&gt;{product.title}&lt;/h3&gt;<br>            &lt;p&gt;${product.price}&lt;/p&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/InfiniteScroll&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ProductList;</pre><p><strong>Flow </strong>:</p><pre>import React, { useEffect, useState } from &quot;react&quot;;<br><br>interface Product {<br>  id: number;<br>  title: string;<br>  price: number;<br>}<br><br>interface ProductResponse {<br>  data: Product[];<br>  pagination: {<br>    currentPage: number;<br>    pageSize: number;<br>    totalItems: number;<br>    totalPages: number;<br>    hasNextPage: boolean;<br>  };<br>}<br><br>const ProductList: React.FC = () =&gt; {<br>  const [products, setProducts] = useState&lt;Product[]&gt;([]);<br>  const [page, setPage] = useState(1);<br>  const [hasMore, setHasMore] = useState(true);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState&lt;string | null&gt;(null);<br><br>  const fetchProducts = async () =&gt; {<br>    if (loading || !hasMore) return;<br><br>    try {<br>      setLoading(true);<br>      setError(null);<br><br>      const response = await fetch(<br>        `/api/products?page=${page}&amp;limit=10`<br>      );<br><br>      if (!response.ok) {<br>        throw new Error(&quot;Failed to fetch products&quot;);<br>      }<br><br>      const result: ProductResponse = await response.json();<br><br>      setProducts((prev) =&gt; [<br>        ...prev,<br>        ...result.data,<br>      ]);<br><br>      setHasMore(result.pagination.hasNextPage);<br><br>      if (result.pagination.hasNextPage) {<br>        setPage((prev) =&gt; prev + 1);<br>      }<br>    } catch (err) {<br>      setError(<br>        err instanceof Error ? err.message : &quot;Something went wrong&quot;<br>      );<br>    } finally {<br>      setLoading(false);<br>    }<br>  };<br><br>  useEffect(() =&gt; {<br>    fetchProducts();<br>  }, []);<br><br>  return (<br>    &lt;div style={{ maxWidth: &quot;600px&quot;, margin: &quot;0 auto&quot; }}&gt;<br>      &lt;h2&gt;Products&lt;/h2&gt;<br><br>      {error &amp;&amp; (<br>        &lt;p style={{ color: &quot;red&quot; }}&gt;<br>          {error}<br>        &lt;/p&gt;<br>      )}<br><br>      &lt;div&gt;<br>        {products.map((product) =&gt; (<br>          &lt;div<br>            key={product.id}<br>            style={{<br>              border: &quot;1px solid #ddd&quot;,<br>              padding: &quot;12px&quot;,<br>              marginBottom: &quot;10px&quot;,<br>              borderRadius: &quot;8px&quot;,<br>            }}<br>          &gt;<br>            &lt;h3&gt;{product.title}&lt;/h3&gt;<br>            &lt;p&gt;${product.price}&lt;/p&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br><br>      {products.length === 0 &amp;&amp; loading &amp;&amp; (<br>        &lt;p&gt;Loading products...&lt;/p&gt;<br>      )}<br><br>      {hasMore &amp;&amp; (<br>        &lt;button<br>          onClick={fetchProducts}<br>          disabled={loading}<br>          style={{<br>            padding: &quot;10px 20px&quot;,<br>            cursor: loading ? &quot;not-allowed&quot; : &quot;pointer&quot;,<br>          }}<br>        &gt;<br>          {loading ? &quot;Loading...&quot; : &quot;Load More&quot;}<br>        &lt;/button&gt;<br>      )}<br><br>      {!hasMore &amp;&amp; products.length &gt; 0 &amp;&amp; (<br>        &lt;p&gt;No more products&lt;/p&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ProductList;</pre><h4>Usage:</h4><pre>&lt;InfiniteScroll<br>  dataLength={products.length}<br>  next={fetchProducts}<br>  hasMore={hasMore}<br>  loader={&lt;p&gt;Loading products...&lt;/p&gt;}<br>&gt;<br>  {products.map((product) =&gt; (<br>    &lt;div key={product.id}&gt;<br>      {product.title} - ₹{product.price}<br>    &lt;/div&gt;<br>  ))}<br>&lt;/InfiniteScroll&gt;</pre><h3>Key props:</h3><ul><li>dataLength → current number of loaded items (required)</li><li>next → function to fetch the next page</li><li>hasMore → controls whether loading continues</li><li>loader → shown while fetching</li><li>endMessage → shown when all data is loaded</li><li>scrollableTarget → tells the component which container to monitor</li></ul><h4>Alternative: Cursor-based pagination (common for large apps)</h4><p>Instead of pages, APIs often return a cursor.</p><h4>Request</h4><p>First request:</p><pre>GET /api/products?limit=10</pre><p>Next request:</p><pre>GET /api/products?limit=10&amp;cursor=eyJpZCI6MTAwfQ==</pre><h3>Response</h3><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;id&quot;: 101,<br>      &quot;title&quot;: &quot;MacBook Pro&quot;,<br>      &quot;price&quot;: 149999<br>    }<br>  ],<br>  &quot;nextCursor&quot;: &quot;eyJpZCI6MTEwfQ==&quot;,<br>  &quot;hasMore&quot;: true<br>}</pre><p>React state:</p><pre>const [cursor, setCursor] = useState&lt;string | null&gt;(null);<br>const [hasMore, setHasMore] = useState(true);<br><br>const fetchProducts = async () =&gt; {<br>  const url = cursor<br>    ? `/api/products?limit=10&amp;cursor=${cursor}`<br>    : `/api/products?limit=10`;<br>  const res = await fetch(url);<br>  const result = await res.json();<br>  setProducts((prev) =&gt; [<br>    ...prev,<br>    ...result.data,<br>  ]);<br>  setCursor(result.nextCursor);<br>  setHasMore(result.hasMore);<br>};</pre><p>For feeds like <strong>Instagram, Twitter/X, Facebook, chat messages</strong>, cursor pagination is usually preferred because it handles new data and large datasets better. For admin tables and simple lists, page-based pagination is usually enough.</p><h3>Avoid duplicate requests</h3><p>A common issue is multiple concurrent fetches when the user scrolls quickly. Guard against this with a loading flag:</p><pre>const [loading, setLoading] = useState(false);<br><br>const fetchMore = async () =&gt; {<br>  if (loading || !hasMore) return;<br>  setLoading(true);<br>  try {<br>    const res = await fetch(`/api/items?page=${page}`);<br>    const data = await res.json();<br>    setItems((prev) =&gt; [...prev, ...data.items]);<br>    setPage((prev) =&gt; prev + 1);<br>    setHasMore(data.hasMore);<br>  } finally {<br>    setLoading(false);<br>  }<br>};</pre><p>This pattern helps prevent duplicate API calls and race conditions during rapid scrolling.</p><h3>Common props</h3><pre>| Prop                | Description                                         |<br>| ------------------- | --------------------------------------------------- |<br>| `dataLength`        | Current number of rendered items.                   |<br>| `next`              | Function called when more data should be loaded.    |<br>| `hasMore`           | Whether more data is available.                     |<br>| `loader`            | Component shown while loading.                      |<br>| `endMessage`        | Displayed when all data has been loaded.            |<br>| `scrollThreshold`   | When to trigger loading (default `0.8`).            |<br>| `scrollableTarget`  | ID of a scrollable container instead of the window. |<br>| `inverse`           | Enables chat-style loading from the top.            |<br>| `pullDownToRefresh` | Enables pull-to-refresh on supported devices.       |</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=778c061d1b7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>