<?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 Dolapavan on Medium]]></title>
        <description><![CDATA[Stories by Dolapavan on Medium]]></description>
        <link>https://medium.com/@dolapavan?source=rss-25b3cd8d553e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kV4VecygNx_4FOj0</url>
            <title>Stories by Dolapavan on Medium</title>
            <link>https://medium.com/@dolapavan?source=rss-25b3cd8d553e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:11:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dolapavan/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[Phase 8 Complete Notes: AWS RDS + EKS Integration]]></title>
            <link>https://medium.com/@dolapavan/phase-8-complete-notes-aws-rds-eks-integration-8ba66c4a5694?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba66c4a5694</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws-eks]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 19:15:56 GMT</pubDate>
            <atom:updated>2026-01-30T19:15:56.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>Goal</h3><p>Migrate from in-cluster PostgreSQL (StatefulSets with PVCs) to AWS RDS for production-grade stateful microservices architecture.</p><h3>Architecture Transformation</h3><h3>Before (Phase 7)</h3><pre>┌─────────────────────────────────────┐<br>│         EKS Cluster                 │<br>│  ┌──────────┐  ┌──────────┐        │<br>│  │ order-   │  │ order-db │        │<br>│  │ service  │──│ (pod+PVC)│        │<br>│  └──────────┘  └──────────┘        │<br>│                                     │<br>│  Similar for user-db, notif-db...  │<br>└─────────────────────────────────────┘</pre><p><strong>Issues with this approach:</strong></p><ul><li>Data tied to K8s lifecycle</li><li>Manual backup management</li><li>Complex StatefulSet configuration</li><li>Risk of data loss on PVC issues</li></ul><h3>After (Phase 8)</h3><pre>┌─────────────────────────────────────┐<br>│         EKS Cluster                 │<br>│  ┌──────────┐                       │<br>│  │ order-   │───┐                   │<br>│  │ service  │   │                   │<br>│  └──────────┘   │                   │<br>│  ┌──────────┐   │                   │<br>│  │ user-    │   │                   │<br>│  │ service  │───┤                   │<br>│  └──────────┘   │                   │<br>│  ┌──────────┐   │                   │<br>│  │ notif-   │   │                   │<br>│  │ service  │───┘                   │<br>│  └──────────┘   │                   │<br>└──────────────────┼───────────────────┘<br>                   ▼<br>    ┌──────────────────────────────┐<br>    │    AWS RDS (Managed)         │<br>    │  ┌────────────────────────┐  │<br>    │  │ PostgreSQL 16.11       │  │<br>    │  │ - orderdb              │  │<br>    │  │ - userdb               │  │<br>    │  │ - notificationdb       │  │<br>    │  │ + Auto backups (7 days)│  │<br>    │  │ + Point-in-time recov. │  │<br>    │  └────────────────────────┘  │<br>    └──────────────────────────────┘</pre><p><strong>Benefits:</strong></p><ul><li>Data independent of K8s</li><li>AWS manages backups, updates, HA</li><li>Point-in-time recovery</li><li>Professional database management</li></ul><h3>Step-by-Step Implementation</h3><h3>Part A: VPC Infrastructure Setup</h3><h4>Commands Used</h4><pre># 1. Create VPC<br>aws ec2 create-vpc \<br>  --cidr-block 10.0.0.0/16 \<br>  --region us-east-2 \<br>  --tag-specifications &#39;ResourceType=vpc,Tags=[{Key=Name,Value=dola-microservices-vpc}]&#39;<br># Saved: VPC_ID=vpc-02cf8dc2d6354588d<br># 2. Create Internet Gateway<br>aws ec2 create-internet-gateway \<br>  --region us-east-2 \<br>  --tag-specifications &#39;ResourceType=internet-gateway,Tags=[{Key=Name,Value=dola-igw}]&#39;<br># Saved: IGW_ID<br># 3. Attach IGW to VPC<br>aws ec2 attach-internet-gateway \<br>  --vpc-id $VPC_ID \<br>  --internet-gateway-id $IGW_ID \<br>  --region us-east-2<br># 4. Create 2 subnets in different AZs (required for RDS)<br>aws ec2 create-subnet \<br>  --vpc-id $VPC_ID \<br>  --cidr-block 10.0.1.0/24 \<br>  --availability-zone us-east-2a \<br>  --tag-specifications &#39;ResourceType=subnet,Tags=[{Key=Name,Value=dola-public-subnet-2a}]&#39;<br># Saved: SUBNET_1=subnet-0bfb8019f62ccc4a7<br>aws ec2 create-subnet \<br>  --vpc-id $VPC_ID \<br>  --cidr-block 10.0.2.0/24 \<br>  --availability-zone us-east-2b \<br>  --tag-specifications &#39;ResourceType=subnet,Tags=[{Key=Name,Value=dola-public-subnet-2b}]&#39;<br># Saved: SUBNET_2=subnet-0f9244803a95c18b0<br># 5. Create and configure route table<br>aws ec2 create-route-table --vpc-id $VPC_ID<br>aws ec2 create-route --route-table-id $RT_ID --destination-cidr-block 0.0.0.0/0 --gateway-id $IGW_ID<br>aws ec2 associate-route-table --subnet-id $SUBNET_1 --route-table-id $RT_ID<br>aws ec2 associate-route-table --subnet-id $SUBNET_2 --route-table-id $RT_ID<br># 6. Enable auto-assign public IP<br>aws ec2 modify-subnet-attribute --subnet-id $SUBNET_1 --map-public-ip-on-launch<br>aws ec2 modify-subnet-attribute --subnet-id $SUBNET_2 --map-public-ip-on-launch</pre><h3>Part B: RDS Instance Setup</h3><h4>Issue 1: IAM Permission Denied</h4><p><strong>Error:</strong></p><pre>User: arn:aws:iam::279715468177:user/dola-eks-admin is not authorized to perform: rds:CreateDBSubnetGroup</pre><p><strong>Root Cause:</strong></p><ul><li>IAM permissions are service-specific</li><li>EKSFullAccess policy only gives eks:* permissions</li><li>RDS is a separate service requiring rds:* permissions</li></ul><p><strong>Solution:</strong></p><pre># Add RDS permissions<br>aws iam attach-user-policy \<br>  --user-name dola-eks-admin \<br>  --policy-arn arn:aws:iam::aws:policy/AmazonRDSFullAccess</pre><p><strong>Learning:</strong></p><ul><li>AWS uses principle of least privilege</li><li>Each service requires explicit permissions</li><li>Managed policies (like AmazonRDSFullAccess) grant broad service access</li><li>Custom policies can be more restrictive</li></ul><h4>Commands Used</h4><pre># 1. Create DB subnet group<br>aws rds create-db-subnet-group \<br>  --db-subnet-group-name dola-rds-subnet-group \<br>  --db-subnet-group-description &quot;Subnets for microservices RDS&quot; \<br>  --subnet-ids $SUBNET_1 $SUBNET_2 \<br>  --region us-east-2<br># 2. Create security group for RDS<br>aws ec2 create-security-group \<br>  --group-name dola-rds-sg \<br>  --description &quot;Security group for RDS PostgreSQL&quot; \<br>  --vpc-id $VPC_ID \<br>  --region us-east-2<br># Saved: RDS_SG=sg-07476a39ac486285b<br># 3. Allow PostgreSQL traffic from VPC<br>aws ec2 authorize-security-group-ingress \<br>  --group-id $RDS_SG \<br>  --protocol tcp \<br>  --port 5432 \<br>  --cidr 10.0.0.0/16 \<br>  --region us-east-2</pre><h4>Issue 2: PostgreSQL Version Not Available</h4><p><strong>Error:</strong></p><pre>Cannot find version 16.1 for postgres</pre><p><strong>Root Cause:</strong></p><ul><li>AWS regions have different available versions</li><li>Must check available versions before specifying</li></ul><p><strong>Solution:</strong></p><pre># Check available versions<br>aws rds describe-db-engine-versions \<br>  --engine postgres \<br>  --region us-east-2 \<br>  --query &quot;DBEngineVersions[?contains(EngineVersion, &#39;16&#39;)].EngineVersion&quot;<br># Found: 16.6, 16.8, 16.9, 16.10, 16.11<br># Used: 16.11 (latest)</pre><h4>Issue 3: Command Syntax Errors</h4><p><strong>Error:</strong></p><pre>zsh: number expected (from &#39;!&#39; in password)<br>Unknown options: false (from --no-multi-az)</pre><p><strong>Root Cause:</strong></p><ul><li>Shell interprets special characters like ! in passwords</li><li>AWS CLI boolean flags use --no- prefix, not --flag false</li></ul><p><strong>Solution:</strong></p><pre># Fixed password: Removed special chars<br>--master-user-password Dola2026SecurePass<br># Fixed boolean flags<br>--no-publicly-accessible  # instead of --publicly-accessible false</pre><h4>Final RDS Creation Command</h4><pre>aws rds create-db-instance \<br>  --db-instance-identifier dola-microservices-db \<br>  --db-instance-class db.t3.micro \<br>  --engine postgres \<br>  --engine-version 16.11 \<br>  --master-username dbadmin \<br>  --master-user-password Dola2026SecurePass \<br>  --allocated-storage 20 \<br>  --storage-type gp3 \<br>  --vpc-security-group-ids $RDS_SG \<br>  --db-subnet-group-name dola-rds-subnet-group \<br>  --backup-retention-period 7 \<br>  --preferred-backup-window &quot;03:00-04:00&quot; \<br>  --preferred-maintenance-window &quot;mon:04:00-mon:05:00&quot; \<br>  --enable-cloudwatch-logs-exports postgresql \<br>  --no-publicly-accessible \<br>  --region us-east-2 \<br>  --tags Key=Name,Value=dola-microservices-db Key=Environment,Value=learning</pre><p><strong>Result:</strong></p><ul><li>RDS Endpoint: dola-microservices-db.c3q4g8ougfdk.us-east-2.rds.amazonaws.com</li><li>Creation time: ~8 minutes</li><li>Status progression: creating → backing-up → available</li></ul><h3>Part C: EKS Cluster Setup</h3><h4>Commands Used</h4><pre># 1. Create/verify EKS cluster IAM role<br>aws iam create-role \<br>  --role-name dola-microservices-eks-role \<br>  --assume-role-policy-document &#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [{<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {&quot;Service&quot;: &quot;eks.amazonaws.com&quot;},<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>    }]<br>  }&#39;aws iam attach-role-policy \<br>  --role-name dola-microservices-eks-role \<br>  --policy-arn arn:aws:iam::aws:policy/AmazonEKSClusterPolicy<br># 2. Create EKS cluster<br>aws eks create-cluster \<br>  --name dola-microservices \<br>  --role-arn arn:aws:iam::279715468177:role/dola-microservices-eks-role \<br>  --resources-vpc-config subnetIds=$SUBNET_1,$SUBNET_2 \<br>  --region us-east-2<br># Wait time: ~12 minutes<br># Status: CREATING → ACTIVE<br># 3. Update kubeconfig<br>aws eks update-kubeconfig \<br>  --name dola-microservices \<br>  --region us-east-2<br># 4. Create node group IAM role<br>aws iam create-role \<br>  --role-name dola-eks-node-role \<br>  --assume-role-policy-document &#39;{...}&#39;<br>aws iam attach-role-policy --role-name dola-eks-node-role \<br>  --policy-arn arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy<br>aws iam attach-role-policy --role-name dola-eks-node-role \<br>  --policy-arn arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy<br>aws iam attach-role-policy --role-name dola-eks-node-role \<br>  --policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly<br># 5. Create node group<br>aws eks create-nodegroup \<br>  --cluster-name dola-microservices \<br>  --nodegroup-name dola-nodes \<br>  --node-role arn:aws:iam::279715468177:role/dola-eks-node-role \<br>  --subnets $SUBNET_1 $SUBNET_2 \<br>  --instance-types t3.medium \<br>  --scaling-config minSize=2,maxSize=2,desiredSize=2 \<br>  --region us-east-2<br># Wait time: ~5 minutes<br># Result: 2 nodes in Ready state<br></pre><h3>Part D: Database Setup in RDS</h3><h4>Create Databases and Users</h4><pre># Connect to RDS using psql client pod<br>kubectl run psql-client --rm -it --image=postgres:16 --restart=Never -- bash<br># Inside pod:<br>psql -h dola-microservices-db.c3q4g8ougfdk.us-east-2.rds.amazonaws.com \<br>     -U dbadmin \<br>     -d postgres<br># Password: Dola2026SecurePass</pre><p><strong>SQL Commands:</strong></p><pre>-- Create databases<br>CREATE DATABASE orderdb;<br>CREATE DATABASE userdb;<br>CREATE DATABASE notificationdb;<br>-- Create separate users<br>CREATE USER orderuser WITH PASSWORD &#39;order_pass_2026&#39;;<br>CREATE USER useruser WITH PASSWORD &#39;user_pass_2026&#39;;<br>CREATE USER notificationuser WITH PASSWORD &#39;notif_pass_2026&#39;;<br>-- Grant database privileges<br>GRANT ALL PRIVILEGES ON DATABASE orderdb TO orderuser;<br>GRANT ALL PRIVILEGES ON DATABASE userdb TO useruser;<br>GRANT ALL PRIVILEGES ON DATABASE notificationdb TO notificationuser;</pre><h4>Issue 4: PostgreSQL 15+ Permission Denied</h4><p><strong>Error:</strong></p><pre>org.postgresql.util.PSQLException: ERROR: permission denied for schema public<br>Position: 14<br>Error executing DDL &quot;create sequence users_seq start with 1 increment by 50&quot; via JDBC</pre><p><strong>Root Cause:</strong></p><ul><li><strong>Major PostgreSQL change in version 15+</strong></li><li>Before v15: PUBLIC role had CREATE permission on public schema by default</li><li>After v15: This permission removed for security</li><li>AWS RDS PostgreSQL 16.11 follows this new security model</li></ul><p><strong>Why This Happened:</strong></p><ul><li>Granting ALL PRIVILEGES ON DATABASE only gives connection rights</li><li>Does NOT grant schema-level permissions</li><li>Users need explicit GRANT ALL ON SCHEMA public to create tables/sequences</li></ul><p><strong>Solution (Run for Each Database):</strong></p><pre>-- Connect to each database<br>\c orderdb<br>GRANT ALL ON SCHEMA public TO orderuser;<br>GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO orderuser;<br>GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO orderuser;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO orderuser;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO orderuser;<br>\c userdb<br>GRANT ALL ON SCHEMA public TO useruser;<br>GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO useruser;<br>GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO useruser;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO useruser;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO useruser;<br>\c notificationdb<br>GRANT ALL ON SCHEMA public TO notificationuser;<br>GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO notificationuser;<br>GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO notificationuser;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO notificationuser;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO notificationuser;</pre><p><strong>What Each Command Does:</strong></p><ul><li>GRANT ALL ON SCHEMA public: Allows creating objects in schema</li><li>GRANT ALL PRIVILEGES ON ALL TABLES: Access existing tables</li><li>GRANT ALL PRIVILEGES ON ALL SEQUENCES: Access existing sequences</li><li>ALTER DEFAULT PRIVILEGES: Ensures future objects are accessible</li></ul><p><strong>Learning:</strong></p><ul><li>Always check PostgreSQL version-specific changes</li><li>Schema permissions ≠ database permissions</li><li>Production databases need careful permission setup</li><li>This is a real-world issue you’d encounter in production</li></ul><h4>Issue 5: psql Multi-Line Command Parsing</h4><p><strong>Error:</strong></p><pre>invalid integer value &quot;all&quot; for connection option &quot;port&quot;<br>invalid integer value &quot;privileges&quot; for connection option &quot;port&quot;</pre><p><strong>Root Cause:</strong></p><ul><li>Copy-pasting multiple commands at once</li><li>\c (connect) command on one line, SQL on next line</li><li>psql tries to parse second line as connection parameters</li></ul><p><strong>Solution:</strong></p><ul><li>Run commands <strong>one at a time</strong></li><li>Wait for \c to complete before running SQL</li><li>Don’t copy-paste multi-line blocks in psql</li></ul><h3>Part E: Kubernetes Secrets and Deployments</h3><h4>Create Secrets for Database Credentials</h4><pre># Order-service secret<br>kubectl create secret generic order-db-secret \<br>  --from-literal=DB_HOST=dola-microservices-db.c3q4g8ougfdk.us-east-2.rds.amazonaws.com \<br>  --from-literal=DB_PORT=5432 \<br>  --from-literal=DB_NAME=orderdb \<br>  --from-literal=DB_USER=orderuser \<br>  --from-literal=DB_PASSWORD=order_pass_2026<br># User-service secret<br>kubectl create secret generic user-db-secret \<br>  --from-literal=DB_HOST=dola-microservices-db.c3q4g8ougfdk.us-east-2.rds.amazonaws.com \<br>  --from-literal=DB_PORT=5432 \<br>  --from-literal=DB_NAME=userdb \<br>  --from-literal=DB_USER=useruser \<br>  --from-literal=DB_PASSWORD=user_pass_2026<br># Notification-service secret<br>kubectl create secret generic notification-db-secret \<br>  --from-literal=DB_HOST=dola-microservices-db.c3q4g8ougfdk.us-east-2.rds.amazonaws.com \<br>  --from-literal=DB_PORT=5432 \<br>  --from-literal=DB_NAME=notificationdb \<br>  --from-literal=DB_USER=notificationuser \<br>  --from-literal=DB_PASSWORD=notif_pass_2026</pre><p><strong>Why Kubernetes Secrets?</strong></p><ul><li>Credentials not hardcoded in YAML</li><li>Base64 encoded (not encrypted, but obfuscated)</li><li>Can be injected as environment variables</li><li>Production: Use AWS Secrets Manager or External Secrets Operator</li></ul><h4>Updated Deployment YAML (Example: order-service)</h4><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: order-service<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: order-service<br>  template:<br>    metadata:<br>      labels:<br>        app: order-service<br>    spec:<br>      containers:<br>      - name: order-service<br>        image: dola26/order-service:1.1<br>        ports:<br>        - containerPort: 8082<br>        env:<br>        - name: DB_HOST<br>          valueFrom:<br>            secretKeyRef:<br>              name: order-db-secret<br>              key: DB_HOST<br>        - name: DB_PORT<br>          valueFrom:<br>            secretKeyRef:<br>              name: order-db-secret<br>              key: DB_PORT<br>        - name: DB_NAME<br>          valueFrom:<br>            secretKeyRef:<br>              name: order-db-secret<br>              key: DB_NAME<br>        - name: SPRING_DATASOURCE_URL<br>          value: &quot;jdbc:postgresql://$(DB_HOST):$(DB_PORT)/$(DB_NAME)&quot;<br>        - name: SPRING_DATASOURCE_USERNAME<br>          valueFrom:<br>            secretKeyRef:<br>              name: order-db-secret<br>              key: DB_USER<br>        - name: SPRING_DATASOURCE_PASSWORD<br>          valueFrom:<br>            secretKeyRef:<br>              name: order-db-secret<br>              key: DB_PASSWORD<br>        - name: KAFKA_BOOTSTRAP_SERVERS<br>          value: &quot;kafka:9092&quot;<br>        - name: USER_SERVICE_URL<br>          value: &quot;http://user-service:8081&quot;<br>        livenessProbe:<br>          httpGet:<br>            path: /actuator/health<br>            port: 8082<br>          initialDelaySeconds: 60<br>          periodSeconds: 10<br>        readinessProbe:<br>          httpGet:<br>            path: /actuator/health<br>            port: 8082<br>          initialDelaySeconds: 30<br>          periodSeconds: 5<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: order-service<br>spec:<br>  selector:<br>    app: order-service<br>  ports:<br>  - protocol: TCP<br>    port: 8082<br>    targetPort: 8082<br>  type: ClusterIP</pre><p><strong>Key Changes from Previous Deployments:</strong></p><ul><li>No database StatefulSets/PVCs</li><li>Database connection via secrets</li><li>Services now stateless (data in RDS)</li></ul><h3>Part F: Kafka Issues</h3><h4>Issue 6: Kafka Image Requires KRaft Configuration</h4><p><strong>Error:</strong></p><pre>Error: environment variable &quot;KAFKA_PROCESS_ROLES&quot; is not set</pre><p><strong>Root Cause:</strong></p><ul><li>Newer Confluent Kafka images (7.x+) use KRaft mode (Kafka without Zookeeper)</li><li>Requires additional configuration: KAFKA_PROCESS_ROLES, KAFKA_NODE_ID, KAFKA_CONTROLLER_QUORUM_VOTERS</li><li>More complex for learning purposes</li></ul><p><strong>Solution:</strong></p><ul><li>Switched to wurstmeister/kafka:2.13-2.8.1 image</li><li>Uses traditional Zookeeper mode</li><li>Simpler configuration for development/learning</li></ul><p><strong>Updated Kafka Deployment:</strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: kafka<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: kafka<br>  template:<br>    metadata:<br>      labels:<br>        app: kafka<br>    spec:<br>      enableServiceLinks: false<br>      containers:<br>      - name: kafka<br>        image: wurstmeister/kafka:2.13-2.8.1<br>        ports:<br>        - containerPort: 9092<br>        env:<br>        - name: KAFKA_BROKER_ID<br>          value: &quot;1&quot;<br>        - name: KAFKA_ZOOKEEPER_CONNECT<br>          value: &quot;zookeeper:2181&quot;<br>        - name: KAFKA_ADVERTISED_LISTENERS<br>          value: &quot;PLAINTEXT://kafka:9092&quot;<br>        - name: KAFKA_LISTENERS<br>          value: &quot;PLAINTEXT://0.0.0.0:9092&quot;<br>        - name: KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR<br>          value: &quot;1&quot;<br>        - name: KAFKA_AUTO_CREATE_TOPICS_ENABLE<br>          value: &quot;true&quot;</pre><h4>Issue 7: Zookeeper Stale Broker Registration</h4><p><strong>Error:</strong></p><pre>ERROR: node already exists and owner &#39;72057671674691585&#39; does not match current session &#39;72057671674691590&#39;<br>Fatal error during KafkaServer startup<br>org.apache.zookeeper.KeeperException$NodeExistsException</pre><p><strong>Root Cause:</strong></p><ul><li>Kafka broker registered with Zookeeper in previous session</li><li>Pod restarted but Zookeeper kept old ephemeral node</li><li>New Kafka pod can’t register with same broker ID</li></ul><p><strong>Solution:</strong></p><pre># Delete Zookeeper pod to clear state<br>kubectl delete pod -l app=zookeeper<br># Wait for restart<br>kubectl get pods -l app=zookeeper -w<br># Then delete Kafka pod<br>kubectl delete pod -l app=kafka</pre><p><strong>Alternative (Manual Cleanup):</strong></p><pre># Connect to Zookeeper<br>kubectl exec -it &lt;zookeeper-pod&gt; -- /bin/bash<br># Inside Zookeeper pod<br>/apache-zookeeper-3.8.0-bin/bin/zkCli.sh -server localhost:2181<br># Inside zkCli<br>deleteall /brokers/ids/1<br>quit</pre><p><strong>Learning:</strong></p><ul><li>Zookeeper uses ephemeral nodes for broker registration</li><li>Ephemeral nodes should auto-delete when session closes</li><li>Sometimes cleanup fails, requiring manual intervention</li><li>In production: Use Kafka KRaft mode or managed Kafka (MSK)</li></ul><h4>Issue 8: Hardcoded Kafka Port in Application Code</h4><p><strong>Error (in order-service logs):</strong></p><pre>Bootstrap broker kafka:29092 (id: -1 rack: null) disconnected<br>Disconnecting from node -1 due to socket connection setup timeout</pre><p><strong>Root Cause:</strong></p><ul><li>application.properties had hardcoded: spring.kafka.bootstrap-servers=kafka:29092</li><li>Kubernetes env var KAFKA_BOOTSTRAP_SERVERS=kafka:9092 didn&#39;t override it</li><li>Spring Boot property precedence: file properties &gt; environment variables (by default)</li></ul><p><strong>Debugging Steps:</strong></p><pre># 1. Checked Kubernetes deployment<br>kubectl get deployment order-service -o yaml | grep KAFKA<br># Showed: kafka:9092 <br># 2. Checked logs<br>kubectl logs -l app=order-service | grep kafka<br># Showed: kafka:29092 <br># 3. Tested connectivity from pod<br>kubectl exec -it &lt;order-service-pod&gt; -- bash<br>curl -v telnet://kafka:9092<br># Connection successful (so Kafka is reachable)<br># Conclusion: Application code has wrong port</pre><p><strong>Solution:</strong></p><p>Updated application.properties:</p><pre># Before (hardcoded):<br>spring.kafka.bootstrap-servers=kafka:29092<br># After (environment-aware):<br>spring.kafka.bootstrap-servers=${KAFKA_BOOTSTRAP_SERVERS:kafka:9092}</pre><p><strong>Syntax Explanation:</strong></p><ul><li>${ENV_VAR:default} means: &quot;Use ENV_VAR if set, else use default&quot;</li><li>Allows environment to override properties file</li><li>Best practice for 12-factor apps</li></ul><p><strong>Rebuild and redeploy:</strong></p><pre>cd ~/Documents/order-management-microservices/order-service<br>docker buildx build --platform linux/amd64 -t dola26/order-service:1.1 --push .<br>kubectl set image deployment/order-service order-service=dola26/order-service:1.1</pre><p><strong>Same fix applied to notification-service.</strong></p><h4>Issue 9: Kafka Topic Not Auto-Created</h4><p><strong>Error:</strong></p><pre>org.apache.kafka.common.errors.TimeoutException: Topic order-events not present in metadata after 60000 ms</pre><p><strong>Root Cause:</strong></p><ul><li>KAFKA_AUTO_CREATE_TOPICS_ENABLE=true was set</li><li>But auto-creation failed due to producer timeout</li><li>Kafka needs time to create topic on first write</li></ul><p><strong>Solution:</strong></p><pre># Manually create topic<br>kubectl exec -it $(kubectl get pod -l app=kafka -o jsonpath=&#39;{.items[0].metadata.name}&#39;) -- bash<br># Inside Kafka pod<br>kafka-topics.sh --create \<br>  --bootstrap-server localhost:9092 \<br>  --replication-factor 1 \<br>  --partitions 3 \<br>  --topic order-events<br># Verify<br>kafka-topics.sh --list --bootstrap-server localhost:9092</pre><p><strong>Why Manual Creation is Better in Production:</strong></p><ul><li>Explicit control over partitions (affects parallelism)</li><li>Explicit replication factor (affects durability)</li><li>Prevents accidental topic creation</li><li>Topic configuration is infrastructure-as-code</li></ul><h3>Part G: Testing and Verification</h3><h4>Test 1: Create User</h4><pre>kubectl port-forward svc/user-service 8081:8081<br>curl -X POST http://localhost:8081/users \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;name&quot;: &quot;Dola Kabotula&quot;,<br>    &quot;email&quot;: &quot;dola@example.com&quot;<br>  }&#39;<br># Response:<br>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;Dola Kabotula&quot;,<br>  &quot;email&quot;: &quot;dola@example.com&quot;<br>}</pre><h4>Test 2: Create Order</h4><pre>kubectl port-forward svc/order-service 8082:8082<br>curl -X POST http://localhost:8082/orders \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;userId&quot;: 1,<br>    &quot;product&quot;: &quot;Complete RDS Test&quot;,<br>    &quot;quantity&quot;: 10<br>  }&#39;<br># Response:<br>{<br>  &quot;id&quot;: 1,<br>  &quot;userId&quot;: 1,<br>  &quot;product&quot;: &quot;Complete RDS Test&quot;,<br>  &quot;quantity&quot;: 10,<br>  &quot;status&quot;: &quot;CREATED&quot;<br>}</pre><h4>Test 3: Verify Kafka Event Flow</h4><pre>kubectl logs -l app=notification-service --tail=30<br># Output:<br>Received OrderCreatedEvent from Kafka - Order ID: 1, User ID: 1<br>Notification sent - To User: 1, Type: EMAIL, Message: Order #1 created</pre><h4>Test 4: Data Persistence (Phase 8 Milestone!)</h4><pre># Delete ALL pods<br>kubectl delete pod --all<br># Wait for restart<br>kubectl get pods -w<br># All pods come back Running<br># Verify data survived<br>kubectl port-forward svc/user-service 8081:8081<br>curl http://localhost:8081/users<br># Response: Shows user created before pod deletion <br>kubectl port-forward svc/order-service 8082:8082<br>curl http://localhost:8082/orders<br># Response: Shows order created before pod deletion </pre><p><strong>Result: SUCCESS! Data persists in RDS independent of pod lifecycle.</strong></p><h3>Debugging Techniques Used</h3><h3>1. Systematic Layer-by-Layer Debugging</h3><p>When issues occurred, debugged from bottom to top:</p><ol><li><strong>Network layer:</strong> Can pods reach each other?</li><li><strong>DNS layer:</strong> Does service name resolve?</li><li><strong>Application layer:</strong> Are services configured correctly?</li></ol><p>Example (Kafka connectivity):</p><pre># Layer 1: DNS<br>kubectl exec -it &lt;pod&gt; -- nslookup kafka<br># Layer 2: Network<br>kubectl exec -it &lt;pod&gt; -- curl -v telnet://kafka:9092<br># Layer 3: Application<br>kubectl logs -l app=order-service | grep kafka</pre><h3>2. Log Analysis</h3><pre># Recent logs<br>kubectl logs -l app=service-name --tail=50<br># Follow logs in real-time<br>kubectl logs -l app=service-name -f<br># Logs from all replicas<br>kubectl logs -l app=service-name --all-containers=true<br># Search for specific errors<br>kubectl logs -l app=service-name | grep -i error</pre><h3>3. Pod Inspection</h3><pre># Get pod status<br>kubectl get pods -l app=service-name<br># Describe pod (events, conditions)<br>kubectl describe pod &lt;pod-name&gt;<br># Check environment variables<br>kubectl exec &lt;pod-name&gt; -- env | grep DB<br># Interactive troubleshooting<br>kubectl exec -it &lt;pod-name&gt; -- bash</pre><h3>4. Network Testing</h3><pre># Create test pod with network tools<br>kubectl run nettest --rm -it --image=nicolaka/netshoot -- bash<br># Inside test pod:<br>nslookup kafka<br>nc -zv kafka 9092<br>curl http://order-service:8082/actuator/health</pre><h3>5. Kubernetes Resource Inspection</h3><pre># Check service<br>kubectl get svc kafka<br>kubectl describe svc kafka<br># Check deployment<br>kubectl get deployment order-service -o yaml<br># Check secrets<br>kubectl get secrets<br>kubectl describe secret order-db-secret</pre><h3>6. AWS CLI Verification</h3><pre># Check RDS status<br>aws rds describe-db-instances \<br>  --db-instance-identifier dola-microservices-db \<br>  --region us-east-2<br># Check security groups<br>aws ec2 describe-security-groups \<br>  --group-ids $RDS_SG \<br>  --region us-east-2</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba66c4a5694" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phase 7: AWS EKS Deployment — Complete Learning Notes]]></title>
            <link>https://medium.com/@dolapavan/phase-7-aws-eks-deployment-complete-learning-notes-02930c207968?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/02930c207968</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 03:27:08 GMT</pubDate>
            <atom:updated>2026-01-30T03:27:08.332Z</atom:updated>
            <content:encoded><![CDATA[<h3>Phase 7: AWS EKS Deployment — Complete Learning Notes</h3><h3>Architecture Overview</h3><h3>What We Built on AWS</h3><pre>┌─────────────────────────────────────────────────────────────────────────────┐<br>│                              AWS Cloud (us-east-2)                          │<br>│                                                                             │<br>│  ┌───────────────────────────────────────────────────────────────────────┐ │<br>│  │                         VPC (10.0.0.0/16)                             │ │<br>│  │                                                                        │ │<br>│  │   ┌─────────────────────┐       ┌─────────────────────┐              │ │<br>│  │   │   Public Subnet     │       │   Public Subnet     │              │ │<br>│  │   │   10.0.1.0/24       │       │   10.0.2.0/24       │              │ │<br>│  │   │   (us-east-2a)      │       │   (us-east-2b)      │              │ │<br>│  │   │                     │       │                     │              │ │<br>│  │   │  ┌──────────────┐   │       │  ┌──────────────┐   │              │ │<br>│  │   │  │ Worker Node  │   │       │  │ Worker Node  │   │              │ │<br>│  │   │  │ (t3.medium)  │   │       │  │ (t3.medium)  │   │              │ │<br>│  │   │  └──────────────┘   │       │  └──────────────┘   │              │ │<br>│  │   └─────────────────────┘       └─────────────────────┘              │ │<br>│  │              │                            │                           │ │<br>│  │              └──────────┬─────────────────┘                           │ │<br>│  │                         │                                             │ │<br>│  │                         ▼                                             │ │<br>│  │            ┌─────────────────────────┐                               │ │<br>│  │            │    Internet Gateway      │                               │ │<br>│  │            └─────────────────────────┘                               │ │<br>│  └───────────────────────────────────────────────────────────────────────┘ │<br>│                                                                             │<br>│  ┌───────────────────────────────────────────────────────────────────────┐ │<br>│  │              EKS Control Plane (Managed by AWS)                       │ │<br>│  │   ┌─────────────┐  ┌─────────────┐  ┌─────────────┐                  │ │<br>│  │   │ API Server  │  │    etcd     │  │  Scheduler  │                  │ │<br>│  │   └─────────────┘  └─────────────┘  └─────────────┘                  │ │<br>│  └───────────────────────────────────────────────────────────────────────┘ │<br>└─────────────────────────────────────────────────────────────────────────────┘</pre><h3>Deployed Microservices</h3><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                    Kubernetes Pods (11 total)                    │<br>│                                                                  │<br>│  Services:                        Databases:                     │<br>│  ├── order-service (2 replicas)   ├── order-db (PostgreSQL)     │<br>│  ├── user-service (2 replicas)    ├── user-db (PostgreSQL)      │<br>│  └── notification-service (2)     └── notification-db (PgSQL)   │<br>│                                                                  │<br>│  Infrastructure:                                                 │<br>│  ├── kafka (1 replica)                                          │<br>│  └── zookeeper (1 replica)                                      │<br>└─────────────────────────────────────────────────────────────────┘</pre><h3>Step-by-Step Deployment Process</h3><h3>Phase 1: IAM Permissions Setup</h3><p><strong>What:</strong> Configure IAM user with necessary permissions to manage EKS.</p><p><strong>Commands:</strong></p><pre># Check current user<br>aws sts get-caller-identity<br># List attached policies<br>aws iam list-attached-user-policies --user-name dola-eks-admin<br># Create custom EKS policy (if needed)<br>aws iam create-policy \\<br>  --policy-name EKSFullAccess \\<br>  --policy-document &#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;eks:*&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}&#39;<br># Attach policy to user<br>aws iam attach-user-policy \\<br>  --user-name dola-eks-admin \\<br>  --policy-arn arn:aws:iam::YOUR_ACCOUNT_ID:policy/EKSFullAccess</pre><p><strong>Required Policies:</strong></p><ul><li>AmazonEC2FullAccess - For creating VPC, subnets, EC2 instances</li><li>IAMFullAccess - For creating IAM roles</li><li>EKSFullAccess (custom) - For EKS cluster management</li></ul><h3>Phase 2: VPC and Networking Setup</h3><p><strong>What:</strong> Create isolated network infrastructure for EKS.</p><p><strong>Why:</strong> EKS needs a VPC with at least 2 subnets in different Availability Zones for high availability.</p><pre># 1. Create VPC<br>aws ec2 create-vpc --region us-east-2 --cidr-block 10.0.0.0/16 \\<br>  --query &#39;Vpc.VpcId&#39; --output text<br># Result: vpc-0f12080f78f2d51a1<br># 2. Enable DNS (required for EKS)<br>aws ec2 modify-vpc-attribute --region us-east-2 \\<br>  --vpc-id vpc-0f12080f78f2d51a1 --enable-dns-hostnames<br>aws ec2 modify-vpc-attribute --region us-east-2 \\<br>  --vpc-id vpc-0f12080f78f2d51a1 --enable-dns-support<br># 3. Create subnets in different AZs<br>aws ec2 create-subnet --region us-east-2 \\<br>  --vpc-id vpc-0f12080f78f2d51a1 \\<br>  --cidr-block 10.0.1.0/24 \\<br>  --availability-zone us-east-2a \\<br>  --query &#39;Subnet.SubnetId&#39; --output text<br># Result: subnet-0ce410eaa0efc3bca<br>aws ec2 create-subnet --region us-east-2 \\<br>  --vpc-id vpc-0f12080f78f2d51a1 \\<br>  --cidr-block 10.0.2.0/24 \\<br>  --availability-zone us-east-2b \\<br>  --query &#39;Subnet.SubnetId&#39; --output text<br># Result: subnet-0eff9d8e9e2538503<br># 4. Create Internet Gateway<br>aws ec2 create-internet-gateway --region us-east-2 \\<br>  --query &#39;InternetGateway.InternetGatewayId&#39; --output text<br># Result: igw-0a83a1a03107216cc<br># 5. Attach IGW to VPC<br>aws ec2 attach-internet-gateway --region us-east-2 \\<br>  --internet-gateway-id igw-0a83a1a03107216cc \\<br>  --vpc-id vpc-0f12080f78f2d51a1<br># 6. Create Route Table<br>aws ec2 create-route-table --region us-east-2 \\<br>  --vpc-id vpc-0f12080f78f2d51a1 \\<br>  --query &#39;RouteTable.RouteTableId&#39; --output text<br># Result: rtb-003a937a6bf61eac7<br># 7. Add route to internet<br>aws ec2 create-route --region us-east-2 \\<br>  --route-table-id rtb-003a937a6bf61eac7 \\<br>  --destination-cidr-block 0.0.0.0/0 \\<br>  --gateway-id igw-0a83a1a03107216cc<br># 8. Associate route table with subnets<br>aws ec2 associate-route-table --region us-east-2 \\<br>  --route-table-id rtb-003a937a6bf61eac7 \\<br>  --subnet-id subnet-0ce410eaa0efc3bca<br>aws ec2 associate-route-table --region us-east-2 \\<br>  --route-table-id rtb-003a937a6bf61eac7 \\<br>  --subnet-id subnet-0eff9d8e9e2538503<br># 9. Enable auto-assign public IPs<br>aws ec2 modify-subnet-attribute --region us-east-2 \\<br>  --subnet-id subnet-0ce410eaa0efc3bca \\<br>  --map-public-ip-on-launch<br>aws ec2 modify-subnet-attribute --region us-east-2 \\<br>  --subnet-id subnet-0eff9d8e9e2538503 \\<br>  --map-public-ip-on-launch</pre><p><strong>Network Architecture:</strong></p><pre>VPC: 10.0.0.0/16<br>├── Subnet 1: 10.0.1.0/24 (us-east-2a) - Public<br>├── Subnet 2: 10.0.2.0/24 (us-east-2b) - Public<br>├── Internet Gateway: Attached<br>└── Route Table: 0.0.0.0/0 → Internet Gateway</pre><h3>Phase 3: EKS Cluster Creation</h3><p><strong>What:</strong> Create the Kubernetes control plane (managed by AWS).</p><pre># 1. Create EKS cluster role (if doesn&#39;t exist)<br>aws iam create-role \\<br>  --role-name dola-microservices-eks-role \\<br>  --assume-role-policy-document &#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>      {<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Principal&quot;: {<br>          &quot;Service&quot;: &quot;eks.amazonaws.com&quot;<br>        },<br>        &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>      }<br>    ]<br>  }&#39;<br># Attach required policies<br>aws iam attach-role-policy \\<br>  --role-name dola-microservices-eks-role \\<br>  --policy-arn arn:aws:iam::aws:policy/AmazonEKSClusterPolicy<br># 2. Create EKS cluster (takes 15-20 minutes)<br>aws eks create-cluster \\<br>  --region us-east-2 \\<br>  --name dola-microservices \\<br>  --role-arn arn:aws:iam::YOUR_ACCOUNT_ID:role/dola-microservices-eks-role \\<br>  --resources-vpc-config subnetIds=subnet-0ce410eaa0efc3bca,subnet-0eff9d8e9e2538503<br># 3. Check status<br>aws eks describe-cluster --region us-east-2 \\<br>  --name dola-microservices \\<br>  --query &#39;cluster.status&#39; --output text<br># Wait until: ACTIVE<br># 4. Configure kubectl<br>aws eks update-kubeconfig --region us-east-2 --name dola-microservices<br># 5. Verify connection<br>kubectl get nodes  # Shows empty (no worker nodes yet)</pre><h3>Phase 4: Node Group Creation</h3><p><strong>What:</strong> Create EC2 worker nodes to run your pods.</p><pre># 1. Create node role<br>aws iam create-role \\<br>  --role-name dola-eks-node-role \\<br>  --assume-role-policy-document &#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>      {<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Principal&quot;: {<br>          &quot;Service&quot;: &quot;ec2.amazonaws.com&quot;<br>        },<br>        &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>      }<br>    ]<br>  }&#39;<br># 2. Attach required policies<br>aws iam attach-role-policy --role-name dola-eks-node-role \\<br>  --policy-arn arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy<br>aws iam attach-role-policy --role-name dola-eks-node-role \\<br>  --policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly<br>aws iam attach-role-policy --role-name dola-eks-node-role \\<br>  --policy-arn arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy<br># 3. Create node group (takes 3-5 minutes)<br>aws eks create-nodegroup \\<br>  --region us-east-2 \\<br>  --cluster-name dola-microservices \\<br>  --nodegroup-name dola-nodes \\<br>  --node-role arn:aws:iam::YOUR_ACCOUNT_ID:role/dola-eks-node-role \\<br>  --subnets subnet-0ce410eaa0efc3bca subnet-0eff9d8e9e2538503 \\<br>  --instance-types t3.medium \\<br>  --scaling-config minSize=2,maxSize=3,desiredSize=2 \\<br>  --disk-size 20<br># 4. Verify nodes<br>kubectl get nodes<br># Should show 2 nodes with STATUS: Ready<br></pre><h3>Phase 5: EBS CSI Driver Installation</h3><p><strong>What:</strong> Install the driver that allows Kubernetes to create EBS volumes for persistent storage.</p><p><strong>Why:</strong> EKS doesn’t include this by default. Without it, PersistentVolumeClaims stay in “Pending” state.</p><pre># 1. Get OIDC issuer URL<br>aws eks describe-cluster --name dola-microservices --region us-east-2 \\<br>  --query &#39;cluster.identity.oidc.issuer&#39; --output text<br># Result: &lt;https://oidc.eks.us-east-2.amazonaws.com/id/9A02EAE38A3C70BA31728232655AE147&gt;<br># 2. Create OIDC provider<br>aws iam create-open-id-connect-provider \\<br>  --url &lt;https://oidc.eks.us-east-2.amazonaws.com/id/9A02EAE38A3C70BA31728232655AE147&gt; \\<br>  --client-id-list sts.amazonaws.com \\<br>  --thumbprint-list 9e99a48a9960b14926bb7f3b02e22da2b0ab7280 \\<br>  --region us-east-2<br># 3. Create IAM role for EBS CSI driver<br>aws iam create-role \\<br>  --role-name AmazonEKS_EBS_CSI_DriverRole \\<br>  --assume-role-policy-document &#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>      {<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Principal&quot;: {<br>          &quot;Federated&quot;: &quot;arn:aws:iam::YOUR_ACCOUNT_ID:oidc-provider/oidc.eks.us-east-2.amazonaws.com/id/YOUR_OIDC_ID&quot;<br>        },<br>        &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,<br>        &quot;Condition&quot;: {<br>          &quot;StringEquals&quot;: {<br>            &quot;oidc.eks.us-east-2.amazonaws.com/id/YOUR_OIDC_ID:aud&quot;: &quot;sts.amazonaws.com&quot;,<br>            &quot;oidc.eks.us-east-2.amazonaws.com/id/YOUR_OIDC_ID:sub&quot;: &quot;system:serviceaccount:kube-system:ebs-csi-controller-sa&quot;<br>          }<br>        }<br>      }<br>    ]<br>  }&#39;<br># 4. Attach policy<br>aws iam attach-role-policy \\<br>  --role-name AmazonEKS_EBS_CSI_DriverRole \\<br>  --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy<br># 5. Install EBS CSI addon with the role<br>aws eks create-addon \\<br>  --cluster-name dola-microservices \\<br>  --addon-name aws-ebs-csi-driver \\<br>  --service-account-role-arn arn:aws:iam::YOUR_ACCOUNT_ID:role/AmazonEKS_EBS_CSI_DriverRole \\<br>  --region us-east-2<br># 6. Verify CSI driver is running<br>kubectl get pods -n kube-system | grep ebs</pre><h3>Phase 6: Deploy Applications</h3><p><strong>What:</strong> Deploy your microservices to EKS.</p><pre># 1. Deploy in order (dependencies first)<br>kubectl apply -f postgres-config-configmap.yaml<br>kubectl apply -f order-db-pvc.yaml<br>kubectl apply -f order-db-deployment.yaml<br>kubectl apply -f user-db-pvc.yaml<br>kubectl apply -f user-db-deployment.yaml<br>kubectl apply -f notification-db-pvc.yaml<br>kubectl apply -f notification-db-deployment.yaml<br>kubectl apply -f zookeeper-deployment.yaml<br>kubectl apply -f kafka-deployment.yaml<br>kubectl apply -f order-service-configmap.yaml<br>kubectl apply -f user-service-configmap.yaml<br>kubectl apply -f notification-service-configmap.yaml<br>kubectl apply -f order-service-service.yaml<br>kubectl apply -f user-service-service.yaml<br>kubectl apply -f notification-service-service.yaml<br>kubectl apply -f order-service-deployment.yaml<br>kubectl apply -f user-service-deployment.yaml<br>kubectl apply -f notification-service-deployment.yaml<br># 2. Verify all pods running<br>kubectl get pods</pre><h3>Problems Faced and Solutions</h3><h3>Problem 1: IAM Permission Denied for EKS</h3><p><strong>Symptom:</strong></p><pre>An error occurred (AccessDeniedException) when calling the ListClusters operation:<br>User: arn:aws:iam::XXX:user/dola-eks-admin is not authorized to perform: eks:ListClusters</pre><p><strong>Root Cause:</strong> IAM user missing EKS permissions.</p><p><strong>Solution:</strong></p><pre># Create and attach custom EKS policy<br>aws iam create-policy --policy-name EKSFullAccess --policy-document &#39;{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [{&quot;Effect&quot;: &quot;Allow&quot;, &quot;Action&quot;: &quot;eks:*&quot;, &quot;Resource&quot;: &quot;*&quot;}]<br>}&#39;<br>aws iam attach-user-policy --user-name dola-eks-admin \\<br>  --policy-arn arn:aws:iam::YOUR_ACCOUNT_ID:policy/EKSFullAccess<br></pre><p><strong>Lesson:</strong> AWS managed policies like AmazonEKSClusterPolicy are for service roles, not user permissions.</p><h3>Problem 2: Docker Image Platform Mismatch</h3><p><strong>Symptom:</strong></p><pre>Failed to pull image &quot;dola26/order-service:1.0&quot;: no match for platform in manifest: not found</pre><p><strong>Root Cause:</strong> Images built on Mac M1/M2 (ARM) don’t run on EKS nodes (AMD64/x86).</p><p><strong>Solution:</strong></p><pre># Rebuild images for AMD64 platform<br>cd /path/to/order-service<br>docker buildx build --platform linux/amd64 -t dola26/order-service:1.0 --push .<br>cd /path/to/user-service<br>docker buildx build --platform linux/amd64 -t dola26/user-service:1.0 --push .<br>cd /path/to/notification-service<br>docker buildx build --platform linux/amd64 -t dola26/notification-service:1.0 --push .</pre><p><strong>Lesson:</strong> Always build multi-platform images or target linux/amd64 for cloud deployments.</p><h3>Problem 3: PersistentVolumeClaim Stuck in Pending</h3><p><strong>Symptom:</strong></p><pre>kubectl get pvc<br>NAME           STATUS    STORAGECLASS   AGE<br>order-db-pvc   Pending                  10m</pre><p><strong>Root Cause 1:</strong> Missing storageClassName in PVC.</p><p><strong>Solution 1:</strong> Add storageClassName: gp2 to PVC:</p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: order-db-pvc<br>spec:<br>  storageClassName: gp2  # &lt;-- ADD THIS<br>  accessModes:<br>    - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: 1Gi</pre><p><strong>Root Cause 2:</strong> EBS CSI driver not installed.</p><p><strong>Symptom:</strong></p><pre>Waiting for a volume to be created either by the external provisioner &#39;ebs.csi.aws.com&#39;</pre><p><strong>Solution 2:</strong> Install EBS CSI driver addon (see Phase 5).</p><p><strong>Lesson:</strong> EKS doesn’t include storage drivers by default. You must install EBS CSI driver.</p><h3>Problem 4: EBS CSI Driver Crashing (No IAM Credentials)</h3><p><strong>Symptom:</strong></p><pre>kubectl logs -n kube-system ebs-csi-controller-XXX<br>error: &quot;Failed health check: no EC2 IMDS role found&quot;</pre><p><strong>Root Cause:</strong> EBS CSI addon was created without IAM role.</p><p><strong>Solution:</strong></p><pre># Delete and recreate addon with IAM role<br>aws eks delete-addon --cluster-name dola-microservices \\<br>  --addon-name aws-ebs-csi-driver --region us-east-2<br>aws eks create-addon --cluster-name dola-microservices \\<br>  --addon-name aws-ebs-csi-driver \\<br>  --service-account-role-arn arn:aws:iam::YOUR_ACCOUNT_ID:role/AmazonEKS_EBS_CSI_DriverRole \\<br>  --region us-east-2</pre><p><strong>Lesson:</strong> EBS CSI driver needs IAM permissions via IRSA (IAM Roles for Service Accounts).</p><h3>Problem 5: PostgreSQL Crashing with “lost+found” Error</h3><p><strong>Symptom:</strong></p><pre>initdb: error: directory &quot;/var/lib/postgresql/data&quot; exists but is not empty<br>It contains a lost+found directory, perhaps due to it being a mount point.</pre><p><strong>Root Cause:</strong> EBS volumes are formatted with ext4 which creates a lost+found directory. PostgreSQL refuses to initialize in non-empty directories.</p><p><strong>Solution:</strong> Add PGDATA environment variable to use a subdirectory:</p><pre>env:<br>- name: POSTGRES_DB<br>  value: &quot;orderdb&quot;<br>- name: PGDATA<br>  value: &quot;/var/lib/postgresql/data/pgdata&quot;  # &lt;-- ADD THIS<br>volumeMounts:<br>- name: postgres-storage<br>  mountPath: /var/lib/postgresql/data</pre><p><strong>Lesson:</strong> Always set PGDATA when using PostgreSQL with cloud storage.</p><h3>Problem 6: Kafka CrashLoopBackOff (Service Link Chicken-and-Egg)</h3><p><strong>Symptom:</strong></p><pre>Connection to node 1 (kafka/172.20.146.243:29092) could not be established</pre><p>Kafka pod is 0/1 not ready, Service has no endpoints, Kafka can&#39;t connect to itself.</p><p><strong>Root Cause:</strong></p><ol><li>Kafka advertises kafka:29092 which resolves to Service IP</li><li>Service only routes to Ready pods</li><li>Kafka isn’t Ready → Service has no endpoints → Kafka can’t connect → stays not Ready</li></ol><p><strong>Solution:</strong> Configure Kafka to use localhost for inter-broker communication:</p><pre>env:<br>- name: KAFKA_LISTENERS<br>  value: &quot;INTERNAL://0.0.0.0:29092,EXTERNAL://0.0.0.0:9092&quot;<br>- name: KAFKA_ADVERTISED_LISTENERS<br>  value: &quot;INTERNAL://localhost:29092,EXTERNAL://kafka:9092&quot;  # localhost for internal!<br>- name: KAFKA_LISTENER_SECURITY_PROTOCOL_MAP<br>  value: &quot;INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT&quot;<br>- name: KAFKA_INTER_BROKER_LISTENER_NAME<br>  value: &quot;INTERNAL&quot;  # Use INTERNAL listener for broker-to-broker</pre><p>Also use simpler TCP probes:</p><pre>readinessProbe:<br>  tcpSocket:<br>    port: 9092<br>  initialDelaySeconds: 30<br>  periodSeconds: 10</pre><p><strong>Lesson:</strong> In Kubernetes, single-replica Kafka should use localhost for inter-broker communication to avoid service discovery issues.</p><h3>Debugging Methodology</h3><h3>Step 1: Check Pod Status</h3><pre>kubectl get pods<br>kubectl describe pod &lt;pod-name&gt;</pre><h3>Step 2: Check Logs</h3><pre>kubectl logs &lt;pod-name&gt;<br>kubectl logs &lt;pod-name&gt; --previous  # If pod crashed<br>kubectl logs -l app=&lt;label&gt; --tail=50  # By label</pre><h3>Step 3: Check Events</h3><pre>kubectl get events --sort-by=&#39;.lastTimestamp&#39;<br>kubectl describe pod &lt;pod-name&gt; | grep -A20 &quot;Events:&quot;</pre><h3>Step 4: Check PVC/PV Status</h3><pre>kubectl get pvc<br>kubectl describe pvc &lt;pvc-name&gt;</pre><h3>Step 5: Check Service Endpoints</h3><pre>kubectl get endpoints<br>kubectl describe service &lt;service-name&gt;</pre><h3>Step 6: Check Node Resources</h3><pre>kubectl describe nodes<br>kubectl top nodes  # If metrics-server installed</pre><h3>Common Status Meanings</h3><p>Status Meaning Common Fix Pending Waiting for resources Check PVC, node capacity ImagePullBackOff Can&#39;t pull Docker image Check image name, platform CrashLoopBackOff Container keeps crashing Check logs ContainerCreating Setting up container Wait, or check events Running but 0/1 Container running but not ready Check readiness probe</p><h3>Cost Management</h3><h3>EKS Costs (us-east-2)</h3><p>Component Cost EKS Control Plane $0.10/hour (~$73/month) t3.medium instance $0.0416/hour each EBS Storage (gp2) $0.10/GB/month</p><p><strong>Our Setup:</strong></p><ul><li>Control plane: $0.10/hr</li><li>2x t3.medium nodes: $0.0832/hr</li><li>3x 1GB EBS volumes: ~$0.30/month</li><li><strong>Total: ~$0.18/hour = ~$4.32/day</strong></li></ul><h3>Cleanup Commands</h3><pre># 1. Delete node group (3-5 min)<br>aws eks delete-nodegroup --cluster-name dola-microservices \\<br>  --nodegroup-name dola-nodes --region us-east-2<br># Wait for deletion<br>aws eks describe-nodegroup --cluster-name dola-microservices \\<br>  --nodegroup-name dola-nodes --region us-east-2 --query &#39;nodegroup.status&#39;<br># 2. Delete cluster (5-10 min)<br>aws eks delete-cluster --name dola-microservices --region us-east-2<br># 3. Delete VPC resources<br># Get VPC ID<br>VPC_ID=$(aws ec2 describe-vpcs --region us-east-2 \\<br>  --filters &quot;Name=cidr,Values=10.0.0.0/16&quot; \\<br>  --query &#39;Vpcs[0].VpcId&#39; --output text)<br># Delete subnets<br>aws ec2 describe-subnets --region us-east-2 \\<br>  --filters &quot;Name=vpc-id,Values=$VPC_ID&quot; \\<br>  --query &#39;Subnets[*].SubnetId&#39; --output text | \\<br>  xargs -n1 aws ec2 delete-subnet --region us-east-2 --subnet-id<br># Detach and delete IGW<br>IGW_ID=$(aws ec2 describe-internet-gateways --region us-east-2 \\<br>  --filters &quot;Name=attachment.vpc-id,Values=$VPC_ID&quot; \\<br>  --query &#39;InternetGateways[0].InternetGatewayId&#39; --output text)<br>aws ec2 detach-internet-gateway --region us-east-2 \\<br>  --internet-gateway-id $IGW_ID --vpc-id $VPC_ID<br>aws ec2 delete-internet-gateway --region us-east-2 \\<br>  --internet-gateway-id $IGW_ID<br># Delete VPC<br>aws ec2 delete-vpc --region us-east-2 --vpc-id $VPC_ID<br># 4. Delete IAM roles (optional)<br>aws iam detach-role-policy --role-name dola-eks-node-role \\<br>  --policy-arn arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy<br>aws iam delete-role --role-name dola-eks-node-role</pre><h3>Commands Reference</h3><h3>EKS Cluster Management</h3><pre># List clusters<br>aws eks list-clusters --region us-east-2<br># Describe cluster<br>aws eks describe-cluster --name CLUSTER_NAME --region us-east-2<br># Update kubeconfig<br>aws eks update-kubeconfig --name CLUSTER_NAME --region us-east-2</pre><h3>Node Group Management</h3><pre># List node groups<br>aws eks list-nodegroups --cluster-name CLUSTER_NAME --region us-east-2<br># Describe node group<br>aws eks describe-nodegroup --cluster-name CLUSTER_NAME \\<br>  --nodegroup-name NODEGROUP_NAME --region us-east-2<br># Scale node group<br>aws eks update-nodegroup-config --cluster-name CLUSTER_NAME \\<br>  --nodegroup-name NODEGROUP_NAME --region us-east-2 \\<br>  --scaling-config minSize=1,maxSize=3,desiredSize=2</pre><h3>Kubectl Essentials</h3><pre># Get all resources<br>kubectl get all<br># Watch pods<br>kubectl get pods -w<br># Describe resource<br>kubectl describe pod/service/deployment NAME<br># Logs<br>kubectl logs POD_NAME<br>kubectl logs -f POD_NAME  # Follow<br>kubectl logs -l app=LABEL  # By label<br># Execute into pod<br>kubectl exec -it POD_NAME -- /bin/sh<br># Port forward<br>kubectl port-forward svc/SERVICE_NAME LOCAL_PORT:REMOTE_PORT<br># Delete resources<br>kubectl delete pod/deployment/service NAME<br>kubectl delete -f FILE.yaml</pre><h3>Summary: What Made EKS Different from Minikube</h3><p>Aspect Minikube EKS Setup Single command VPC + IAM + Cluster + Nodes Storage Works out of box Need EBS CSI driver Images Any platform Must be linux/amd64 Cost Free ~$0.18/hour Networking Simple VPC, subnets, security groups IAM Not needed Critical for everything Debugging Straightforward Multiple layers to check</p><p><strong>Key Takeaway:</strong> The Kubernetes concepts are the same, but EKS requires understanding AWS infrastructure (VPC, IAM, EBS) to deploy successfully.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02930c207968" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ingress & Networking Phase — Complete Learning Notes]]></title>
            <link>https://medium.com/@dolapavan/ingress-networking-phase-complete-learning-notes-9290fc2bbe59?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9290fc2bbe59</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 19:52:53 GMT</pubDate>
            <atom:updated>2026-01-28T19:52:53.132Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ingress &amp; Networking Phase — Complete Learning Notes</h3><h3>What Problem Does Ingress Solve?</h3><h3>Before Ingress</h3><pre>Users need to know about internal ports:<br>- order-service runs on port 8082<br>- user-service runs on port 8081<br>- notification-service runs on port 8083<br>Users have to call: http://cluster-ip:8082/orders<br>                    http://cluster-ip:8081/users<br>                    http://cluster-ip:8083/notifications<br>Problems:<br>- Multiple ports = confusing<br>- Not standard HTTP/HTTPS<br>- Can&#39;t use standard ports 80/443<br>- Tightly coupled to internal port knowledge</pre><h3>After Ingress (Now)</h3><pre>Single entry point on standard ports:<br>- http://minikube.local/orders → order-service:8082<br>- http://minikube.local/users → user-service:8081<br>- http://minikube.local/notifications → notification-service:8083 (internal only)<br>Benefits:<br>- Single URL for all APIs<br>- Standard HTTP ports (80/443)<br>- URL-based routing (path-based)<br>- Production-like architecture</pre><h3>Core Ingress Concept</h3><p><strong>Ingress is an automated port-forwarder inside Kubernetes.</strong></p><p>In Phase 5, you manually did:</p><pre>kubectl port-forward svc/order-service 8081:8082</pre><p>With Ingress, Kubernetes does this automatically based on routing rules.</p><h3>The 3 Components of Ingress</h3><h3>1. Ingress Controller (NGINX)</h3><p><strong>What it is:</strong> A reverse proxy running inside Kubernetes</p><p><strong>What it does:</strong></p><ul><li>Listens for incoming HTTP requests</li><li>Reads routing rules from Ingress objects</li><li>Forwards requests to appropriate Services</li><li>Performs load balancing</li></ul><p><strong>In minikube:</strong> Enabled with minikube addons enable ingress</p><h3>2. Ingress Object (YAML)</h3><p><strong>What it is:</strong> Kubernetes configuration that specifies routing rules</p><p><strong>What it contains:</strong></p><ul><li>Host names (virtual hosts)</li><li>URL paths</li><li>Which Service each path routes to</li><li>Which port on that Service</li></ul><p><strong>Example:</strong></p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: api-ingress<br>spec:<br>  rules:<br>  - host: minikube.local<br>    http:<br>      paths:<br>      - path: &quot;/orders&quot;<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: order-service<br>            port:<br>              number: 8082</pre><h3>3. Services</h3><p><strong>What they do:</strong> Route traffic from Ingress to the right pods</p><p><strong>Relationship:</strong></p><pre>Ingress → Service → Pod<br>(router)  (load balancer)  (actual app)</pre><p>Services are STILL NEEDED — Ingress doesn’t replace them!</p><h3>Your Ingress YAML Explained</h3><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: api-ingress<br>  namespace: default<br>spec:<br>  rules:<br>  - host: minikube.local          # Virtual host<br>    http:<br>      paths:<br>      - path: &quot;/orders&quot;           # URL path<br>        pathType: Prefix          # Matches /orders, /orders/1, etc.<br>        backend:<br>          service:<br>            name: order-service   # Send to this Service<br>            port:<br>              number: 8082        # On this port<br>      - path: &quot;/users&quot;<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: user-service<br>            port:<br>              number: 8081</pre><h3>Key Concepts</h3><p><strong>host: minikube.local</strong></p><ul><li>Virtual host routing (like Apache/Nginx)</li><li>Requests must have Host: minikube.local header</li><li>Can have multiple hosts in one Ingress</li></ul><p><strong>path: “/orders”</strong></p><ul><li>URL path-based routing</li><li>pathType: Prefix means /orders matches:</li><li>/orders/1</li><li>/orders/create</li><li>/orders-old (doesn&#39;t match)</li></ul><p><strong>backend service name and port</strong></p><ul><li>Must match the Kubernetes Service name</li><li>Port must be the Service port (not the container port)</li></ul><h3>The Three Layers of Debugging You Learned</h3><h3>Layer 1: Network Connectivity</h3><p><strong>Problem:</strong> Requests hung indefinitely when accessing <a href="http://192.168.49.2/orders/1">http://192.168.49.2/orders/1</a></p><p><strong>Root Cause:</strong></p><pre>Docker driver on macOS runs Minikube inside a Linux VM<br>The IP 192.168.49.2 is internal to Docker&#39;s network<br>Not accessible from your MacBook directly</pre><p><strong>Lesson:</strong> Understand your deployment environment’s networking!</p><p><strong>Solution:</strong> Use minikube service to create a tunnel</p><pre>minikube service ingress-nginx-controller -n ingress-nginx --url<br># Returns: http://127.0.0.1:57126 (accessible from your laptop)</pre><h3>Layer 2: Ingress Virtual Host Routing</h3><p><strong>Problem:</strong> Even with tunnel, requests still hanging</p><p><strong>Root Cause:</strong></p><pre>Ingress was configured with: host: minikube.local<br>But request had: Host: 192.168.49.2 (IP address)</pre><pre>Ingress compares headers:<br>- 192.168.49.2 ≠ minikube.local<br>- No match → request fails</pre><p><strong>How Virtual Host Routing Works:</strong></p><pre>┌─────────────────────────────┬────────────────────┬──────────────────┐<br>│ Request Host Header         │ Ingress Host Rule  │ Result           │<br>├─────────────────────────────┼────────────────────┼──────────────────┤<br>│ localhost                   │ localhost          │ Routes        │<br>│ 192.168.49.2                │ localhost          │ No match      │<br>│ minikube.local              │ minikube.local     │ Routes        │<br>└─────────────────────────────┴────────────────────┴──────────────────┘</pre><p><strong>Solution:</strong> Add Host header to requests</p><pre>curl http://127.0.0.1:57126/orders/1 -H &quot;Host: minikube.local&quot;</pre><p><strong>Why /etc/hosts entry is needed:</strong></p><pre>Without /etc/hosts entry:<br>curl http://minikube.local/orders<br>→ DNS lookup fails (no public record)<br>→ Can&#39;t connect<br>With /etc/hosts entry (192.168.49.2  minikube.local):<br>curl http://minikube.local/orders<br>→ Local /etc/hosts resolves to 192.168.49.2<br>→ Request reaches Minikube<br>→ Host header matches Ingress rule<br>→ Routing works <br></pre><h3>Layer 3: Application Data</h3><p><strong>Problem:</strong> Requests returned 500 errors after routing worked</p><p><strong>Root Cause:</strong></p><pre>Databases were empty<br>No test data to return<br>OrderController threw exception: &quot;Order not found&quot;</pre><p><strong>Solution:</strong> Insert test data</p><pre>kubectl exec deployment/order-db -- psql -U postgres -d orderdb -c \<br>  &quot;INSERT INTO orders (id, user_id, product_name, product_price, status, total, order_date)<br>   VALUES (1, 1, &#39;Laptop&#39;, 999.99, &#39;PENDING&#39;, 999.99, NOW());&quot;</pre><h3>Complete Working Flow</h3><pre>1. User types: curl http://127.0.0.1:57126/orders/1 -H &quot;Host: minikube.local&quot;</pre><pre>2. Request reaches Ingress Controller (NGINX):<br>   - Checks Host header: minikube.local (matches rule)<br>   - Checks path: /orders/1 (matches /orders with Prefix)<br>   - Finds backend: order-service:8082</pre><pre>3. Ingress forwards to Service (order-service):<br>   - Service receives on port 8082<br>   - Load-balances to one of 2 pod IPs<br>   - Forwards to pod&#39;s port 8082 (targetPort)</pre><pre>4. Pod receives request:<br>   - Spring Boot app on port 8082<br>   - OrderController handles /orders/1<br>   - Queries database<br>   - Returns JSON response</pre><pre>5. Response flows back:<br>   Pod → Service → Ingress → User</pre><h3>Service Port vs Container Port (Critical Difference)</h3><p><strong>You learned this the hard way:</strong></p><p>When you had:</p><pre># order-service Service<br>port: 8081          # What external services call<br>targetPort: 8082    # What container listens on<br># user-service Service<br>port: 8081          # SAME PORT!<br>targetPort: 8081</pre><p><strong>This created a conflict:</strong> Two Services couldn’t both use port 8081</p><p><strong>The Fix:</strong></p><pre># order-service Service<br>port: 8082<br>targetPort: 8082<br># user-service Service  <br>port: 8081<br>targetPort: 8081<br># Now Ingress routes to DIFFERENT Service ports<br>- path: &quot;/orders&quot; → service port 8082<br>- path: &quot;/users&quot; → service port 8081</pre><p><strong>Key Insight:</strong></p><ul><li>targetPort = what the actual Spring Boot app listens on (DON’T CHANGE)</li><li>port = what other services use to reach this Service (MUST BE UNIQUE)</li></ul><h3>Your Architecture Now Looks Like</h3><pre>Internet User (or localhost)<br>    ↓<br>Minikube Tunnel (127.0.0.1:57126)<br>    ↓<br>Ingress Controller (NGINX)<br>    ├── Host: minikube.local matching<br>    ├── Path-based routing (/orders, /users, /notifications)<br>    ↓<br>Services (Load balancing &amp; DNS)<br>    ├── order-service (port 8082)<br>    ├── user-service (port 8081)<br>    └── notification-service (port 8083, internal only)<br>    ↓<br>Pods (Running applications)<br>    ├── order-service x2 (Spring Boot on 8082)<br>    ├── user-service x2 (Spring Boot on 8081)<br>    └── notification-service x2 (Spring Boot on 8083)<br>    ↓<br>Databases<br>    ├── order-db (PostgreSQL)<br>    ├── user-db (PostgreSQL)<br>    └── notification-db (PostgreSQL)</pre><h3>Quick Reference: Testing Your System</h3><p><strong>Start the tunnel:</strong></p><pre>minikube service ingress-nginx-controller -n ingress-nginx --url</pre><p><strong>Test the APIs:</strong></p><pre># Replace with actual URL from tunnel command<br>curl http://127.0.0.1:57126/orders/1 -H &quot;Host: minikube.local&quot;<br>curl http://127.0.0.1:57126/users/1 -H &quot;Host: minikube.local&quot;</pre><p><strong>Check everything is healthy:</strong></p><pre>kubectl get pods          # All should be Running 1/1<br>kubectl get ingress       # Should show Address<br>kubectl get svc           # All services listed</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9290fc2bbe59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phase 5: Kubernetes Deployment — Complete Learning Notes]]></title>
            <link>https://medium.com/@dolapavan/phase-5-kubernetes-deployment-complete-learning-notes-12f54995f188?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/12f54995f188</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 03:57:59 GMT</pubDate>
            <atom:updated>2026-01-28T03:57:59.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>Phase 5: Kubernetes Deployment — Complete Learning Notes</h3><h3>Overview of what we are Building:</h3><pre>Your Laptop <br>    ↓<br>Docker Desktop (application)<br>    ↓<br>minikube container (Linux running inside Docker)<br>    ↓<br>Kubernetes cluster (running inside minikube)<br>    ├── Namespace: default<br>    └── Pods (11 total, all healthy):<br>        ├── order-service (2 replicas)<br>        ├── order-db (1)<br>        ├── user-service (2 replicas)<br>        ├── user-db (1)<br>        ├── notification-service (2 replicas)<br>        ├── notification-db (1)<br>        ├── kafka (1)<br>        └── zookeeper (1)</pre><h3>The 3 Core Kubernetes Objects</h3><h3>1. ConfigMap — Configuration Management</h3><p><strong>What it does:</strong> Stores configuration as key-value pairs, separate from code</p><p><strong>Why it matters:</strong> Change configuration without rebuilding Docker images</p><p><strong>Structure:</strong></p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: order-service-config<br>  namespace: default<br>data:<br>  DB_HOST: &quot;order-db&quot;<br>  DB_PORT: &quot;5432&quot;<br>  KAFKA_BROKERS: &quot;kafka:29092&quot;</pre><h3>2. Deployment — Service Management</h3><p><strong>What it does:</strong> Tells Kubernetes how to run your service (image, replicas, health checks)</p><p><strong>Why it matters:</strong> Kubernetes manages scaling, restarts, and monitoring automatically</p><p><strong>Structure:</strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: order-service<br>spec:<br>  replicas: 2                    # 2 copies for resilience<br>  selector:<br>    matchLabels:<br>      app: order-service         # Label to find pods<br>  template:<br>    spec:<br>      containers:<br>      - name: order-service<br>        image: dola26/order-service:1.2<br>        ports:<br>        - containerPort: 8082<br>        envFrom:<br>        - configMapRef:<br>            name: order-service-config<br>        livenessProbe:           # Is it alive?<br>          httpGet:<br>            path: /actuator/health<br>            port: 8082<br>          initialDelaySeconds: 60<br>          periodSeconds: 10<br>        readinessProbe:          # Is it ready for traffic?<br>          httpGet:<br>            path: /actuator/health<br>            port: 8082<br>          initialDelaySeconds: 30<br>          periodSeconds: 5</pre><h3>3. Service — Network Communication</h3><p><strong>What it does:</strong> Exposes deployment pods to network traffic, provides load balancing and DNS</p><p><strong>Why it matters:</strong> Allows services to discover and communicate with each other</p><p><strong>Structure:</strong></p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: order-service<br>spec:<br>  type: ClusterIP              # Internal only (not exposed outside cluster)<br>  selector:<br>    app: order-service         # Route traffic to pods with this label<br>  ports:<br>  - port: 8081                 # External port (what others call)<br>    targetPort: 8082           # Internal port (container listens on)<br>    protocol: TCP</pre><h3>Port Mapping Pattern</h3><pre>user-service: port 8081 → targetPort 8081<br>order-service: port 8081 → targetPort 8082<br>notification-service: port 8083 → targetPort 8083</pre><p><strong>This pattern shows:</strong></p><ul><li>External port (what other services use to reach you)</li><li>Internal port (what your app actually listens on)</li><li>Kubernetes forwards traffic between them automatically</li></ul><h3>PersistentVolumeClaim (PVC) — Data Storage</h3><p><strong>What it does:</strong> Provides persistent storage for databases</p><p><strong>Why it matters:</strong> Database data survives pod crashes and restarts</p><p><strong>Structure:</strong></p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: order-db-pvc<br>spec:<br>  accessModes:<br>    - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: 1Gi</pre><p><strong>Used in Deployment:</strong></p><pre>volumeMounts:<br>- name: postgres-storage<br>  mountPath: /var/lib/postgresql/data<br>volumes:<br>- name: postgres-storage<br>  persistentVolumeClaim:<br>    claimName: order-db-pvc</pre><h3>Health Checks — The Critical Pattern</h3><h3>Liveness Probe</h3><p><strong>Question:</strong> Is the container alive? <strong>Action:</strong> If fails, Kubernetes <strong>kills and restarts</strong> the pod <strong>Use Case:</strong> Detect zombie processes</p><pre>livenessProbe:<br>  httpGet:<br>    path: /actuator/health<br>    port: 8082<br>  initialDelaySeconds: 60      # Wait 60s before first check (cold start)<br>  periodSeconds: 10            # Check every 10 seconds<br>  failureThreshold: 3          # Kill after 3 failures</pre><h3>Readiness Probe</h3><p><strong>Question:</strong> Is the container ready to accept traffic? <strong>Action:</strong> If fails, Kubernetes <strong>removes from load balancer</strong> (doesn’t kill) <strong>Use Case:</strong> Container is running but dependencies aren’t ready yet</p><pre>readinessProbe:<br>  httpGet:<br>    path: /actuator/health<br>    port: 8082<br>  initialDelaySeconds: 30      # Wait 30s (already running from liveness)<br>  periodSeconds: 5             # Check every 5 seconds (more frequent)<br>  failureThreshold: 3</pre><p><strong>Why Different Delays?</strong></p><ul><li>Liveness: 60s = cold start takes time</li><li>Readiness: 30s = container running, checking dependencies</li></ul><h3>Real Problems You Debugged and Fixed</h3><h3>Problem 1: Wrong Docker Image</h3><p><strong>Symptom:</strong> POST /orders returning 404 Not Found</p><p><strong>Root Cause:</strong> dola26/order-service:1.0 contained notification-service JAR, not order-service JAR</p><p><strong>How You Diagnosed It:</strong></p><pre>kubectl logs order-service-pod | head -20<br># Saw: c.d.n.NotificationServiceApplication : Starting NotificationServiceApplication<br># Realized: WRONG app is running!</pre><p><strong>How You Fixed It:</strong></p><pre>cd order-service<br>mvn clean package -DskipTests<br>docker build -t dola26/order-service:1.2 .<br>docker push dola26/order-service:1.2<br>kubectl set image deployment/order-service order-service=dola26/order-service:1.2</pre><p><strong>Learning:</strong> Always check startup logs to confirm the correct application is running.</p><h3>Problem 2: Service Link Pollution (Kafka Crashing)</h3><p><strong>Symptom:</strong> Kafka pod in CrashLoopBackOff with 106+ restarts</p><p><strong>Root Cause:</strong></p><pre>Step 1: Kubernetes Service named &quot;kafka&quot; created<br>Step 2: Kubernetes auto-injects env vars into ALL pods:<br>        KAFKA_PORT=tcp://10.98.134.18:9092<br>        KAFKA_SERVICE_HOST=10.98.134.18<br>        KAFKA_PORT_9092_TCP=tcp://...<br>        ... (many more KAFKA_* vars)<br>Step 3: confluentinc/cp-kafka image reads ALL KAFKA_* env vars<br>Step 4: It finds KAFKA_PORT with invalid format<br>Step 5: Kafka crashes trying to parse it</pre><p><strong>The Real Issue:</strong></p><ul><li>You explicitly set: KAFKA_ADVERTISED_LISTENERS: &quot;PLAINTEXT://kafka:29092,...&quot;</li><li>Kubernetes auto-injected: KAFKA_SERVICE_HOST, KAFKA_PORT_*, etc.</li><li>Kafka got confused which configuration to use</li></ul><p><strong>The Fix:</strong></p><pre>spec:<br>  enableServiceLinks: false    # Tell Kubernetes: &quot;Don&#39;t auto-inject service vars&quot;</pre><p><strong>How This Works:</strong></p><pre>WITHOUT enableServiceLinks: false:<br>- Kubernetes injects KAFKA_SERVICE_HOST, KAFKA_PORT_*, etc.<br>- App receives BOTH explicit config + auto-injected config<br>- Conflict! App crashes</pre><pre>WITH enableServiceLinks: false:<br>- Kubernetes does NOT inject service discovery vars<br>- App only receives your explicit configuration<br>- Works! </pre><p><strong>Learning:</strong> Service naming conflicts with container env vars can cause crashes. Use enableServiceLinks: false when deploying third-party images.</p><h3>Problem 3: JDBC Connection Failures</h3><p><strong>Symptom:</strong> Pods crashing with “Unable to obtain isolated JDBC connection”</p><p><strong>Root Cause:</strong> Database wasn’t deployed yet</p><p><strong>How Diagnosed It:</strong></p><ul><li>Checked logs</li><li>Saw: “Connection to order-db:5432 refused”</li><li>Realized: Database not running</li></ul><p><strong>How Fixed It:</strong></p><ul><li>Deployed PostgreSQL before the service</li><li>Service could then connect</li></ul><p><strong>Learning:</strong> Respect dependency order — deploy dependencies before the services that use them.</p><h3>Kubernetes Networking Learned</h3><h3>DNS Resolution</h3><pre>order-service pod wants to call user-service<br>↓<br>order-service code: curl http://user-service:8081/...<br>↓<br>Kubernetes DNS resolves &quot;user-service&quot; to Service IP<br>↓<br>Service load-balances to one of the user-service pods<br>↓<br>user-service pod receives request</pre><h3>Load Balancing</h3><p>With 2 replicas:</p><ul><li>If pod1 crashes, traffic goes to pod2 (zero downtime)</li><li>If both healthy, traffic distributed between them</li><li>Automatic failover</li></ul><h3>Service Discovery via Environment Variables</h3><p>Kubernetes tells containers about services via environment variables:</p><pre>For Service named &quot;order-service&quot;:<br>- ORDER_SERVICE_SERVICE_HOST=10.96.180.114<br>- ORDER_SERVICE_SERVICE_PORT=8082</pre><p>But better to use DNS names: <a href="http://order-service:8081/">http://order-service:8081</a></p><h3>Debugging Commands You Used</h3><pre># Check all pods<br>kubectl get pods<br># Watch pods live<br>kubectl get pods -w<br># Check pod logs<br>kubectl logs &lt;pod-name&gt;<br># Get last 50 lines<br>kubectl logs &lt;pod-name&gt; --tail=50<br># Follow logs (like tail -f)<br>kubectl logs &lt;pod-name&gt; -f<br># Execute command inside pod<br>kubectl exec -it &lt;pod-name&gt; -- sh<br># Inside pod, test connectivity<br>curl http://user-service:8081/actuator/health<br># Get all services<br>kubectl get services<br># Get all ConfigMaps<br>kubectl get configmap<br># Port forward for local testing<br>kubectl port-forward svc/order-service 8081:8082<br># Check pod details<br>kubectl describe pod &lt;pod-name&gt;</pre><h3>The Files Created</h3><h3>3 Files Per Service (×3 services = 9 files)</h3><p><strong>For each service (order, user, notification):</strong></p><ol><li>&lt;service&gt;-configmap.yaml - Configuration</li><li>&lt;service&gt;-deployment.yaml - How to run</li><li>&lt;service&gt;-service.yaml - Network exposure</li></ol><h3>Database Files (×3 databases = 6 files)</h3><p><strong>For each database:</strong></p><ol><li>&lt;db&gt;-pvc.yaml - Storage</li><li>&lt;db&gt;-deployment.yaml - PostgreSQL pod</li></ol><h3>Infrastructure (2 files)</h3><ol><li>zookeeper-deployment.yaml - Kafka coordinator</li><li>kafka-deployment.yaml - Message broker</li></ol><p><strong>Total: 17 files</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12f54995f188" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phase 4: Event-Driven Architecture with Kafka — Complete Learning Notes]]></title>
            <link>https://medium.com/@dolapavan/phase-4-event-driven-architecture-with-kafka-complete-learning-notes-551cafb07f57?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/551cafb07f57</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 01:30:33 GMT</pubDate>
            <atom:updated>2026-01-25T16:53:09.864Z</atom:updated>
            <content:encoded><![CDATA[<h3>Phase 4: Event-Driven Architecture with Kafka — Complete Learning Notes</h3><h3>The Problem We Solved</h3><h3>Before Phase 4 (Phase 3 — Synchronous)</h3><pre>order-service creates order<br>    ↓<br>order-service calls notification-service endpoint directly (HTTP)<br>    ↓<br>If notification-service is DOWN → Notification fails</pre><p><strong>Problems:</strong></p><ul><li>Tight coupling (order-service knows about notification-service)</li><li>Synchronous blocking (order-service waits for response)</li><li>Data loss (if notification-service is down, notification is lost)</li><li>Hard to scale (can’t easily add new consumers)</li></ul><h3>After Phase 4 (Asynchronous with Kafka)</h3><pre>order-service creates order<br>    ↓<br>order-service emits OrderCreatedEvent to Kafka<br>    ↓<br>Event stored in Kafka topic: &quot;order-events&quot;<br>    ↓<br>notification-service automatically receives event (whenever ready)<br>    ↓<br>No coupling, no data loss, easy to add new consumers</pre><p><strong>Benefits:</strong></p><ul><li>Loose coupling (services don’t know about each other)</li><li>Asynchronous (order-service doesn’t wait)</li><li>Resilience (events queue up if service is down)</li><li>Scalability (easily add analytics-service, audit-service, etc.)</li></ul><h3>Event-Driven Architecture Concepts</h3><h3>What is an Event?</h3><p>An <strong>event</strong> is a message that something happened in your system.</p><p><strong>Example: OrderCreatedEvent</strong></p><pre>{<br>  &quot;orderId&quot;: 1,<br>  &quot;userId&quot;: 1,<br>  &quot;productName&quot;: &quot;Laptop&quot;,<br>  &quot;productPrice&quot;: 1000.0,<br>  &quot;total&quot;: 1000.0,<br>  &quot;status&quot;: &quot;PENDING&quot;,<br>  &quot;createdAt&quot;: &quot;2026-01-24T17:08:00&quot;<br>}</pre><p><strong>Key principle:</strong> Events contain ALL data that consumers need (Event Enrichment pattern).</p><ul><li>Don’t send just IDs</li><li>Include product name, price, etc.</li><li>Consumers shouldn’t need to call other services</li></ul><h3>Publisher vs Consumer</h3><p><strong>Publisher (order-service):</strong></p><ul><li>Creates events</li><li>Sends to message broker (Kafka)</li><li>Doesn’t care who receives them</li><li>Doesn’t wait for response</li></ul><p><strong>Consumer (notification-service):</strong></p><ul><li>Listens for events</li><li>Receives automatically when available</li><li>Processes independently</li><li>Can fail/restart without affecting publisher</li></ul><h3>Event Flow</h3><pre>Publisher                 Message Broker           Consumer<br>(order-service)          (Kafka)                  (notification-service)<br>emit event    ────→      store in topic      ────→   @KafkaListener<br>              publish    &quot;order-events&quot;             receives event<br>No waiting!                                   processes when ready</pre><h3>Kafka Fundamentals</h3><h3>What is Kafka?</h3><p><strong>Kafka is a distributed message broker.</strong> Think of it like a post office:</p><pre>Your house (order-service) → Posts letter → Post office (Kafka) → Mailman → Neighbor (notification-service)<br>    (publisher)              (publish)       (message broker)    (delivery)  (consumer)</pre><h3>Key Concepts</h3><p><strong>1. Topic</strong></p><ul><li>A named channel where messages flow</li><li>Like a mailing list or broadcast channel</li><li>Example: “order-events”, “user-updated”, “payment-completed”</li></ul><p><strong>2. Producer</strong></p><ul><li>Application that sends messages to a topic</li><li>In our case: order-service</li><li>Uses: kafkaTemplate.send(&quot;order-events&quot;, event)</li></ul><p><strong>3. Consumer</strong></p><ul><li>Application that reads messages from a topic</li><li>In our case: notification-service</li><li>Uses: @KafkaListener(topics = &quot;order-events&quot;)</li></ul><p><strong>4. Consumer Group</strong></p><ul><li>Logical grouping of consumers</li><li>Each message is delivered once per group</li><li>Example: “notification-service-group”</li><li>If you have 3 notification-service instances, they share the load</li></ul><p><strong>5. Partition</strong></p><ul><li>Topics are split into partitions for parallelism</li><li>Each partition goes to one consumer in a group</li><li>Allows horizontal scaling</li></ul><h3>Kafka in Docker</h3><p><strong>Our docker-compose.yml:</strong></p><pre>kafka:<br>  image: confluentinc/cp-kafka:7.5.0<br>  ports:<br>    - &quot;9092:9092&quot;         # External (localhost)<br>    - &quot;29092:29092&quot;       # Internal (Docker network)<br>  environment:<br>    KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092</pre><p><strong>Key insight:</strong></p><ul><li>Inside Docker: use kafka:29092</li><li>Outside Docker (local testing): use localhost:9092</li></ul><h3>Implementation Architecture</h3><h3>System Architecture</h3><pre>┌─────────────────────────────────────────────────────────────┐<br>│           Docker Compose Network                            │<br>│                                                              │<br>│  ┌──────────────────┐      ┌──────────────────┐            │<br>│  │  order-service   │      │   order-db       │            │<br>│  │  (port 8082)     ├──────┤  (PostgreSQL)    │            │<br>│  │                  │      └──────────────────┘            │<br>│  │ Creates orders   │                                       │<br>│  │ Publishes events │                                       │<br>│  └──────────────────┘                                       │<br>│         │                                                    │<br>│         │ emit event                                         │<br>│         ↓                                                    │<br>│  ┌──────────────────────────────────────┐                  │<br>│  │    Kafka Broker (kafka:29092)        │                  │<br>│  │  Topic: &quot;order-events&quot;               │                  │<br>│  │  [Event1][Event2][Event3]...         │                  │<br>│  └──────────────────────────────────────┘                  │<br>│         ↑                                                    │<br>│         │ listen                                             │<br>│         │                                                    │<br>│  ┌──────────────────┐     ┌──────────────────┐            │<br>│  │notification-srv  │     │notification-db   │            │<br>│  │ (port 8083)      ├─────┤ (PostgreSQL)     │            │<br>│  │                  │     └──────────────────┘            │<br>│  │@KafkaListener    │                                      │<br>│  │receives events   │                                      │<br>│  │sends emails      │                                      │<br>│  └──────────────────┘                                      │<br>│                                                              │<br>└─────────────────────────────────────────────────────────────┘</pre><h3>Key Code Components</h3><h3>1. OrderCreatedEvent Class</h3><p><strong>Location:</strong> order-service/src/main/java/com/dola/orderservice/events/OrderCreatedEvent.java</p><pre>public class OrderCreatedEvent {<br>    private Long orderId;<br>    private Long userId;<br>    private String productName;<br>    private Double productPrice;<br>    private Double total;<br>    private String status;<br>    private LocalDateTime createdAt;  // ← Important for Jackson issue!<br>// Constructors, getters, setters<br>}</pre><p><strong>Key point:</strong> LocalDateTime createdAt requires special Jackson configuration (JavaTimeModule).</p><h3>2. KafkaConfig for Producer (order-service)</h3><p><strong>Location:</strong> order-service/src/main/java/com/dola/orderservice/config/KafkaConfig.java</p><pre>@Configuration<br>public class KafkaConfig {<br>@Value(&quot;${spring.kafka.bootstrap-servers}&quot;)<br>    private String bootstrapServers;<br>    @Bean<br>    public ProducerFactory&lt;String, OrderCreatedEvent&gt; producerFactory() {<br>        Map&lt;String, Object&gt; configProps = new HashMap&lt;&gt;();<br>        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);<br>        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);<br>        // Create ObjectMapper with LocalDateTime support<br>        ObjectMapper objectMapper = new ObjectMapper();<br>        objectMapper.registerModule(new JavaTimeModule());<br>        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);<br>        JsonSerializer&lt;OrderCreatedEvent&gt; jsonSerializer = new JsonSerializer&lt;&gt;(objectMapper);<br>        return new DefaultKafkaProducerFactory&lt;&gt;(configProps, new StringSerializer(), jsonSerializer);<br>    }<br>    @Bean<br>    public KafkaTemplate&lt;String, OrderCreatedEvent&gt; kafkaTemplate() {<br>        return new KafkaTemplate&lt;&gt;(producerFactory());<br>    }<br>}</pre><p><strong>What it does:</strong></p><ul><li>Creates a KafkaTemplate bean (Spring will auto-inject this)</li><li>Configures Jackson to handle LocalDateTime</li><li>Configures Kafka bootstrap servers</li></ul><h3>3. OrderEventPublisher Service</h3><p><strong>Location:</strong> order-service/src/main/java/com/dola/orderservice/events/OrderEventPublisher.java</p><pre>@Component<br>public class OrderEventPublisher {<br>private final KafkaTemplate&lt;String, OrderCreatedEvent&gt; kafkaTemplate;<br>    public OrderEventPublisher(KafkaTemplate&lt;String, OrderCreatedEvent&gt; kafkaTemplate) {<br>        this.kafkaTemplate = kafkaTemplate;<br>    }<br>    public void publishOrderCreatedEvent(OrderCreatedEvent event) {<br>        System.out.println(&quot;📤 Publishing OrderCreatedEvent to Kafka:&quot;);<br>        System.out.println(&quot;   Order ID: &quot; + event.getOrderId());<br>        kafkaTemplate.send(&quot;order-events&quot;, String.valueOf(event.getOrderId()), event);<br>        System.out.println(&quot;Event published to topic: order-events&quot;);<br>    }<br>}</pre><p><strong>Key points:</strong></p><ul><li>Constructor injection (better than @Autowired)</li><li>kafkaTemplate.send(topic, key, value)</li><li>Topic: “order-events”</li><li>Key: order ID (routes to same partition)</li><li>Value: OrderCreatedEvent object (auto-serialized to JSON)</li></ul><h3>4. OrderController Integration</h3><p><strong>In OrderController.createOrder():</strong></p><pre>@PostMapping<br>public Order createOrder(@RequestBody Order order) {<br>    // Validate user<br>    boolean userExists = userServiceClient.userExists(order.getUserId());<br>    if (!userExists) {<br>        return new ErrorResponse(&quot;User not found&quot;, &quot;...&quot;);<br>    }<br>// Save order<br>    Order savedOrder = orderRepository.save(order);<br>    // ← NEW: Publish event to Kafka<br>    OrderCreatedEvent event = new OrderCreatedEvent(<br>        savedOrder.getId(),<br>        savedOrder.getUserId(),<br>        savedOrder.getProductName(),<br>        savedOrder.getProductPrice(),<br>        savedOrder.getTotal(),<br>        savedOrder.getStatus()<br>    );<br>    orderEventPublisher.publishOrderCreatedEvent(event);<br>    return savedOrder;<br>}</pre><h3>5. KafkaConfig for Consumer (notification-service)</h3><p><strong>Location:</strong> notification-service/src/main/java/com/dola/notificationservice/config/KafkaConfig.java</p><pre>@Configuration<br>@EnableKafka<br>public class KafkaConfig {<br>@Value(&quot;${spring.kafka.bootstrap-servers}&quot;)<br>    private String bootstrapServers;<br>    @Value(&quot;${spring.kafka.consumer.group-id}&quot;)<br>    private String groupId;<br>    @Bean<br>    public ConsumerFactory&lt;String, OrderCreatedEvent&gt; consumerFactory() {<br>        Map&lt;String, Object&gt; configProps = new HashMap&lt;&gt;();<br>        configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);<br>        configProps.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);<br>        configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);<br>        configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);<br>        configProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, &quot;earliest&quot;);<br>        configProps.put(JsonDeserializer.TRUSTED_PACKAGES, &quot;*&quot;);<br>        // Create ObjectMapper with LocalDateTime support<br>        ObjectMapper objectMapper = new ObjectMapper();<br>        objectMapper.registerModule(new JavaTimeModule());<br>        JsonDeserializer&lt;OrderCreatedEvent&gt; jsonDeserializer =<br>            new JsonDeserializer&lt;&gt;(OrderCreatedEvent.class, objectMapper);<br>        return new DefaultKafkaConsumerFactory&lt;&gt;(<br>            configProps,<br>            new StringDeserializer(),<br>            jsonDeserializer<br>        );<br>    }<br>    @Bean<br>    public ConcurrentKafkaListenerContainerFactory&lt;String, OrderCreatedEvent&gt; kafkaListenerContainerFactory() {<br>        ConcurrentKafkaListenerContainerFactory&lt;String, OrderCreatedEvent&gt; factory =<br>            new ConcurrentKafkaListenerContainerFactory&lt;&gt;();<br>        factory.setConsumerFactory(consumerFactory());<br>        return factory;<br>    }<br>}</pre><ul><li>@EnableKafka - Enables @KafkaListener annotation processing</li><li>AUTO_OFFSET_RESET_CONFIG: &quot;earliest&quot; - Start from beginning if no offset</li><li>TRUSTED_PACKAGES: &quot;*&quot; - Allow deserialization of our classes</li></ul><h3>6. OrderEventListener</h3><p><strong>Location:</strong> notification-service/src/main/java/com/dola/notificationservice/events/OrderEventListener.java</p><pre>@Component<br>public class OrderEventListener {<br>@Autowired<br>    private NotificationService notificationService;<br>    @KafkaListener(topics = &quot;order-events&quot;, groupId = &quot;notification-service-group&quot;)<br>    public void handleOrderCreatedEvent(OrderCreatedEvent event) {<br>        System.out.println(&quot;📨 Received OrderCreatedEvent from Kafka:&quot;);<br>        System.out.println(&quot;   Order ID: &quot; + event.getOrderId());<br>        System.out.println(&quot;   User ID: &quot; + event.getUserId());<br>        System.out.println(&quot;   Product: &quot; + event.getProductName());<br>        // Process the event<br>        notificationService.sendOrderNotification(<br>            event.getOrderId(),<br>            event.getUserId(),<br>            event.getProductName()<br>        );<br>        System.out.println(&quot; Notification sent for order: &quot; + event.getOrderId());<br>    }<br>}</pre><p><strong>Magic here:</strong></p><ul><li>@KafkaListener(topics = &quot;order-events&quot;) - Spring automatically listens to this topic</li><li>When event arrives, this method is automatically called</li><li>Event is auto-deserialized from JSON to OrderCreatedEvent object</li></ul><h3>The Jackson LocalDateTime Issue</h3><h3>The Problem</h3><p><strong>Error:</strong> When serializing/deserializing OrderCreatedEvent with LocalDateTime createdAt:</p><pre>com.fasterxml.jackson.databind.exc.InvalidDefinitionException:<br>Cannot find a deserializer for type java.time.LocalDateTime</pre><p><strong>Why?</strong> Jackson’s default ObjectMapper doesn’t know how to handle Java 8+ date/time types.</p><h3>The Solution</h3><p><strong>Step 1: Add jackson-datatype-jsr310 dependency</strong></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.fasterxml.jackson.datatype&lt;/groupId&gt;<br>    &lt;artifactId&gt;jackson-datatype-jsr310&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>Step 2: Register JavaTimeModule in ObjectMapper</strong></p><pre>ObjectMapper objectMapper = new ObjectMapper();<br>objectMapper.registerModule(new JavaTimeModule());<br>objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);</pre><p><strong>What each line does:</strong></p><ul><li>new ObjectMapper() - Create base ObjectMapper</li><li>registerModule(new JavaTimeModule()) - Teach it how to handle LocalDateTime</li><li>disable(WRITE_DATES_AS_TIMESTAMPS) - Use ISO-8601 format instead of epoch milliseconds</li></ul><h3>Example</h3><p><strong>With proper configuration, LocalDateTime is serialized as:</strong></p><pre>{<br>  &quot;createdAt&quot;: &quot;2026-01-24T17:08:00&quot;<br>}</pre><p><strong>Without configuration, it would fail or serialize as:</strong></p><pre>{<br>  &quot;createdAt&quot;: 1737728880000<br>}</pre><h3>Complete Working Example</h3><h3>The Complete Flow</h3><pre>1. User creates order<br>   POST &lt;http://localhost:8082/orders&gt;<br>   {&quot;userId&quot;:1, &quot;productName&quot;:&quot;Laptop&quot;, ...}<br>2. order-service OrderController.createOrder() runs<br>   - Validates user with user-service <br>   - Saves order to database <br>   - Creates OrderCreatedEvent <br>3. orderEventPublisher.publishOrderCreatedEvent(event)<br>   - Serializes OrderCreatedEvent to JSON<br>   - Uses KafkaTemplate to send to &quot;order-events&quot; topic<br>   - Event stored in Kafka <br>4. Kafka broker stores event<br>   - Topic: &quot;order-events&quot;<br>   - Partition assigned by key (order ID)<br>5. notification-service OrderEventListener is triggered<br>   - @KafkaListener receives the event<br>   - Event is deserialized from JSON to OrderCreatedEvent<br>   - handleOrderCreatedEvent() method runs <br>6. NotificationService processes event<br>   - Creates Notification record<br>   - Stores in notification-db <br>   - Logs notification sent <br>7. Both services are done!<br>   - Response sent back to user<br>   - Event processed by notification-service<br>   - No coupling, no waiting, asynchronous! </pre><h3>Application Properties</h3><p><strong>order-service/application.properties:</strong></p><pre>spring.kafka.bootstrap-servers=${KAFKA_BROKERS:kafka:29092}<br>spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer<br>spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer</pre><p><strong>notification-service/application.properties:</strong></p><pre>spring.kafka.bootstrap-servers=${KAFKA_BROKERS:kafka:29092}<br>spring.kafka.consumer.group-id=notification-service-group<br>spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer<br>spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer<br>spring.kafka.consumer.properties.spring.json.trusted.packages=*</pre><h3>Testing &amp; Verification</h3><h3>Test the Complete Flow</h3><pre># Terminal 1: Watch logs<br>docker compose logs -f</pre><pre># Terminal 2: Create user<br>curl -X POST &lt;http://localhost:8081/users&gt; \\<br>  -H &quot;Content-Type: application/json&quot; \\<br>  -d &#39;{&quot;name&quot;:&quot;John&quot;,&quot;email&quot;:&quot;john@example.com&quot;}&#39;</pre><pre># Terminal 2: Create order<br>curl -X POST &lt;http://localhost:8082/orders&gt; \\<br>  -H &quot;Content-Type: application/json&quot; \\<br>  -d &#39;{<br>    &quot;userId&quot;:1,<br>    &quot;productName&quot;:&quot;Laptop&quot;,<br>    &quot;productPrice&quot;:1000.0,<br>    &quot;total&quot;:1000.0,<br>    &quot;status&quot;:&quot;PENDING&quot;<br>  }&#39;</pre><h3>Expected Logs</h3><pre>order-service | Publishing OrderCreatedEvent to Kafka:<br>order-service |    Order ID: 1<br>order-service | Event published to topic: order-events</pre><pre>notification-service | Received OrderCreatedEvent from Kafka:<br>notification-service |    Order ID: 1<br>notification-service | NOTIFICATION SENT:<br>notification-service | Notification sent for order: 1</pre><h3>Test Resilience</h3><p><strong>Verify that notification-service can be down:</strong></p><pre># Stop notification-service<br>docker stop notification-service</pre><pre># Create another order<br>curl -X POST &lt;http://localhost:8082/orders&gt; ...</pre><pre># Event is published to Kafka ✓<br># Event waits in Kafka queue ✓</pre><pre># Restart notification-service<br>docker compose up notification-service</pre><pre># Watch logs - it receives the queued event ✓</pre><h3>Key Learnings</h3><h3>1. The Jackson LocalDateTime Issue</h3><p><strong>Common mistake:</strong> Using LocalDateTime in events without configuring Jackson.</p><p><strong>Solution:</strong> Always register JavaTimeModule when working with Java 8+ date/time types in Kafka.</p><h3>2. Event Enrichment Pattern</h3><p><strong>Don’t do this:</strong></p><pre>{<br>  &quot;orderId&quot;: 1,<br>  &quot;userId&quot;: 1<br>}</pre><p>Then notification-service has to call order-service and user-service for details.</p><p><strong>Do this:</strong></p><pre>{<br>  &quot;orderId&quot;: 1,<br>  &quot;userId&quot;: 1,<br>  &quot;productName&quot;: &quot;Laptop&quot;,<br>  &quot;productPrice&quot;: 1000.0,<br>  &quot;total&quot;: 1000.0,<br>  &quot;createdAt&quot;: &quot;2026-01-24T17:08:00&quot;<br>}</pre><p>Notification-service has everything it needs.</p><h3>3. Spring Boot Auto-Configuration vs Manual</h3><p><strong>Initial approach:</strong> Created config classes but forgot they need to be scanned.</p><p><strong>Final approach:</strong> Let Spring Boot auto-configure with properties, or create explicit config classes with proper ObjectMapper setup for LocalDateTime.</p><h3>4. Constructor Injection Over @Autowired</h3><p><strong>Better:</strong></p><pre>public OrderEventPublisher(KafkaTemplate&lt;String, OrderCreatedEvent&gt; kafkaTemplate) {<br>    this.kafkaTemplate = kafkaTemplate;<br>}</pre><p><strong>vs</strong></p><p><strong>Less ideal:</strong></p><pre>@Autowired<br>private KafkaTemplate&lt;String, OrderCreatedEvent&gt; kafkaTemplate;</pre><p>Constructor injection makes dependencies explicit and testable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=551cafb07f57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phase 3: Service Decomposition-Complete Learning Notes]]></title>
            <link>https://medium.com/@dolapavan/phase-3-service-decomposition-complete-learning-notes-e8c92939f72e?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c92939f72e</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 05:23:10 GMT</pubDate>
            <atom:updated>2026-01-25T16:50:57.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Big Picture</h3><p><strong>Goal:</strong> Transform your monolithic application into independent microservices that can be developed, deployed, and scaled separately.</p><p><strong>Your Journey:</strong></p><pre>Phase 1: Monolith on EC2<br>  ↓<br>Phase 2: Monolith in Docker<br>  ↓<br>Phase 3: Split into Microservices (YOU ARE HERE)<br>  ↓<br>Phase 4+: Orchestrate with Kubernetes</pre><p><strong>Why this matters for your job fair:</strong></p><ul><li>Shows you understand distributed systems</li><li>Demonstrates real-world architecture thinking</li><li>Proves you can handle complexity and failures</li><li>Shows you’ve built actual working systems</li></ul><h3>What Problem Does Microservices Solve?</h3><h3>The Monolith Problem</h3><p><strong>Your Phase 2 monolith had:</strong></p><ul><li>One Spring Boot app</li><li>One database</li><li>All features in one codebase</li><li>All entities (User, Order) together</li></ul><p><strong>Problems this creates:</strong></p><ol><li><strong>Scaling:</strong> If orders are slow, you scale entire app (wastes resources on user-service parts)</li><li><strong>Deployment:</strong> Change to users requires redeploying entire app</li><li><strong>Technology lock-in:</strong> Everything must use same tech stack</li><li><strong>Failure coupling:</strong> If orders fail, entire app might be affected</li><li><strong>Team organization:</strong> Multiple teams can’t work on different features independently</li></ol><p><strong>Example:</strong></p><pre>Monolith App:<br>├── User logic<br>├── Order logic<br>├── Notification logic<br>└── One database with all data<br>Problem: Need to scale orders? Deploy entire app (including user logic you didn&#39;t touch)<br>Problem: Need to update user logic? Risk breaking orders<br>Problem: Database grows huge with all data mixed together</pre><h3>The Microservices Solution</h3><p><strong>Your Phase 3 system:</strong></p><ul><li>user-service (independent app)</li><li>order-service (independent app)</li><li>notification-service (independent app)</li><li>Each with own database</li><li>Each on own port</li><li>Each deployable independently</li></ul><p><strong>Benefits:</strong></p><ol><li><strong>Independent scaling:</strong> Scale only order-service if needed</li><li><strong>Independent deployment:</strong> Update user-service without touching orders</li><li><strong>Technology freedom:</strong> Each service can use different tech (if you want)</li><li><strong>Failure isolation:</strong> order-service down doesn’t crash user-service</li><li><strong>Team autonomy:</strong> Different teams own different services</li></ol><h3>Monolith vs Microservices</h3><h3>Size Comparison</h3><p><strong>Monolith (Phase 2):</strong></p><pre>Order-Management/<br>├── src/<br>│   ├── entities/<br>│   │   ├── User.java<br>│   │   └── Order.java<br>│   ├── repositories/<br>│   │   ├── UserRepository.java<br>│   │   └── OrderRepository.java<br>│   ├── controllers/<br>│   │   ├── UserController.java<br>│   │   └── OrderController.java<br>│   └── OrderManagementApplication.java<br>├── pom.xml<br>├── Dockerfile<br>└── docker-compose.yml (1 app + 1 db)</pre><p><strong>Microservices (Phase 3):</strong></p><pre>order-management-microservices/<br>├── user-service/<br>│   ├── src/<br>│   │   ├── entities/User.java<br>│   │   ├── repositories/UserRepository.java<br>│   │   ├── controllers/UserController.java<br>│   │   └── UserServiceApplication.java<br>│   ├── pom.xml<br>│   └── Dockerfile<br>├── order-service/<br>│   ├── src/<br>│   │   ├── entities/Order.java<br>│   │   ├── repositories/OrderRepository.java<br>│   │   ├── controllers/OrderController.java<br>│   │   ├── clients/UserServiceClient.java  ← NEW!<br>│   │   └── OrderServiceApplication.java<br>│   ├── pom.xml<br>│   └── Dockerfile<br>├── notification-service/<br>│   ├── src/<br>│   │   ├── entities/Notification.java<br>│   │   ├── repositories/NotificationRepository.java<br>│   │   ├── controllers/NotificationController.java<br>│   │   ├── services/NotificationService.java<br>│   │   └── NotificationServiceApplication.java<br>│   ├── pom.xml<br>│   └── Dockerfile<br>└── docker-compose.yml (3 apps + 3 dbs)</pre><h3>Key Differences</h3><p>AspectMonolithMicroservices<strong>Deployment</strong>All features → 1 appEach feature → separate app<strong>Database</strong>One shared databaseEach service owns its data<strong>Communication</strong>In-process method callsHTTP REST calls<strong>Scaling</strong>Scale entire appScale individual services<strong>Failure</strong>One failure can crash appFailures isolated to service<strong>Development</strong>One codebase, one teamMultiple codebases, multiple teams<strong>Complexity</strong>Simple to start, complex at scaleComplex from start, manageable at scale</p><h3>Understanding Service Boundaries</h3><h3>How to Split a Monolith</h3><p><strong>Question: How do you know where to draw the line between services?</strong></p><p><strong>Answer: Bounded Contexts</strong> (from Domain-Driven Design)</p><p>Each service should own one business domain:</p><ul><li><strong>User-service:</strong> Everything about users (create, retrieve, manage)</li><li><strong>Order-service:</strong> Everything about orders (create, retrieve, manage)</li><li><strong>Notification-service:</strong> Everything about notifications (create, send)</li></ul><h3>Your 3 Services Explained</h3><h4>1. user-service (Port 8081, Database: userdb)</h4><p><strong>Responsibility:</strong></p><ul><li>Manage user data</li><li>Provide user information</li><li>Handle user CRUD operations</li></ul><p><strong>What it owns:</strong></p><ul><li>User entity</li><li>User database table</li><li>User REST endpoints</li></ul><p><strong>What it doesn’t own:</strong></p><ul><li>Orders (belongs to order-service)</li><li>Notifications (belongs to notification-service)</li></ul><p><strong>Endpoints:</strong></p><pre>POST /users          - Create user<br>GET /users/{id}      - Get user by ID<br>GET /users           - Get all users</pre><h4>2. order-service (Port 8082, Database: orderdb)</h4><p><strong>Responsibility:</strong></p><ul><li>Manage order data</li><li>Validate users before creating orders</li><li>Handle order CRUD operations</li></ul><p><strong>What it owns:</strong></p><ul><li>Order entity</li><li>Order database table</li><li>Order REST endpoints</li><li>Order business logic (validation)</li></ul><p><strong>What it doesn’t own:</strong></p><ul><li>User data (belongs to user-service)</li><li>Notification sending (belongs to notification-service)</li></ul><p><strong>Special feature:</strong></p><ul><li>Calls user-service to validate users exist before creating orders</li></ul><p><strong>Endpoints:</strong></p><pre>POST /orders         - Create order (validates user first)<br>GET /orders/{id}     - Get order by ID<br>GET /orders          - Get all orders</pre><h4>3. notification-service (Port 8083, Database: notificationdb)</h4><p><strong>Responsibility:</strong></p><ul><li>Store notifications</li><li>Send/log notifications</li><li>Track notification status</li></ul><p><strong>What it owns:</strong></p><ul><li>Notification entity</li><li>Notification database table</li><li>Notification REST endpoints</li><li>Notification business logic</li></ul><p><strong>What it doesn’t own:</strong></p><ul><li>User data (belongs to user-service)</li><li>Order data (belongs to order-service)</li></ul><p><strong>Future feature (Phase 4):</strong></p><ul><li>Will listen for events from order-service automatically</li><li>Will send notifications without being called directly</li></ul><p><strong>Endpoints:</strong></p><pre>POST /notifications/order      - Send order notification<br>GET /notifications/{id}        - Get notification by ID<br>GET /notifications             - Get all notifications<br>POST /notifications/retry      - Retry failed notifications</pre><h3>Building the 3 Services</h3><h3>The Pattern</h3><p>All 3 services follow the same pattern:</p><pre>Spring Boot Application<br>├── Entity (JPA)<br>├── Repository (Spring Data JPA)<br>├── Controller (REST endpoints)<br>├── [Optional] Service (business logic)<br>├── [Optional] Client (inter-service communication)<br>└── application.properties (configuration)</pre><h3>Key Files in Each Service</h3><p><strong>pom.xml</strong></p><p>xml</p><pre>&lt;!-- Spring Boot starter web (for REST endpoints) --&gt;<br>&lt;!-- Spring Data JPA (for database) --&gt;<br>&lt;!-- PostgreSQL driver (for database connection) --&gt;<br>&lt;!-- Spring Boot Actuator (for health checks) --&gt;<br>server.port=8081                # Each service on different port<br>spring.datasource.url=jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME}<br>spring.jpa.hibernate.ddl-auto=update  # Auto-create tables<br>management.endpoints.web.exposure.include=health  # Enable health endpoint</pre><p><strong>application.properties</strong></p><p>properties</p><p><strong>Entity (JPA)</strong></p><p>java</p><pre>@Entity<br>@Table(name = &quot;users&quot;)  // or &quot;orders&quot; or &quot;notifications&quot;<br>public class User {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.AUTO)<br>    private Long id;<br>    // fields...<br>    // getters/setters...<br>}</pre><p><strong>Repository (Spring Data JPA)</strong></p><p>java</p><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    // Automatically provides: save(), findById(), findAll(), delete()<br>}</pre><p><strong>Controller (REST endpoints)</strong></p><p>java</p><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br>    @PostMapping<br>    public User createUser(@RequestBody User user) { ... }<br>    <br>    @GetMapping(&quot;/{id}&quot;)<br>    public User getUser(@PathVariable Long id) { ... }<br>    <br>    @GetMapping<br>    public Iterable&lt;User&gt; getAllUsers() { ... }<br>}</pre><h3>The New Concept: Inter-Service Client</h3><p><strong>Only order-service has this:</strong></p><p>java</p><pre>@Component<br>public class UserServiceClient {<br>    @Autowired<br>    private RestTemplate restTemplate;<br>    <br>    @Value(&quot;${user.service.url:http://localhost:8081}&quot;)<br>    private String userServiceUrl;<br>    <br>    public boolean userExists(Long userId) {<br>        // Call user-service via HTTP<br>        // Retry 3 times if it fails<br>        // Return true/false<br>    }<br>}</pre><p><strong>This is the key difference in microservices:</strong></p><ul><li>Services call each other via HTTP</li><li>Not via direct method calls</li><li>Need to handle failures (service might be down)</li><li>Need retry logic</li></ul><h3>Inter-Service Communication</h3><h3>How order-service Calls user-service</h3><p><strong>The Flow:</strong></p><pre>1. User sends request to order-service:<br>   POST /orders with userId=1<br>2. order-service receives request in OrderController<br>3. OrderController calls UserServiceClient.userExists(1)<br>4. UserServiceClient makes HTTP request:<br>   GET http://user-service:8081/users/1<br>5. user-service responds:<br>   {&quot;id&quot;:1,&quot;name&quot;:&quot;John&quot;,&quot;email&quot;:&quot;john@example.com&quot;}<br>6. UserServiceClient checks: response != null? YES → return true<br>7. OrderController checks: userExists? YES → create order<br>8. Order saved to order-service&#39;s database<br>9. Response sent back to user</pre><h3>Why HTTP, Not Direct Database Queries?</h3><p><strong>Why not:</strong> SELECT * FROM users WHERE id=1 (direct query)?</p><p><strong>Problems:</strong></p><ul><li>order-service would need access to user-service’s database</li><li>Tight coupling (database schema changes break order-service)</li><li>Can’t scale independently (database becomes bottleneck)</li><li>No clear ownership (who manages that database?)</li></ul><p><strong>Why HTTP REST calls:</strong></p><ul><li>Clean separation (each service owns its data)</li><li>Loose coupling (API contract, not internal details)</li><li>Clear boundaries (service-to-service communication)</li><li>Can be monitored/logged/cached</li></ul><p><strong>Analogy:</strong></p><ul><li>Bad: Reading someone’s diary (direct DB access)</li><li>Good: Asking them a question (HTTP API)</li></ul><h3>Service Discovery</h3><p><strong>How does order-service find user-service?</strong></p><p><strong>In Docker Compose:</strong></p><p>yaml</p><pre>services:<br>  user-service:<br>    container_name: user-service<br>    <br>  order-service:<br>    environment:<br>      USER_SERVICE_URL: http://user-service:8081</pre><p><strong>Magic:</strong> Docker’s internal DNS resolves user-service → IP address of user-service container</p><p><strong>In order-service code:</strong></p><p>java</p><pre>@Value(&quot;${user.service.url:http://localhost:8081}&quot;)<br>private String userServiceUrl;</pre><p><strong>This works because:</strong></p><ul><li>Docker Compose creates a network</li><li>All services on that network</li><li>Service names resolve to IPs (like DNS)</li><li>http://user-service:8081 reaches the user-service container</li></ul><h3>Docker Compose for Microservices</h3><h3>The Master Orchestration File</h3><p><strong>Purpose:</strong> Define and run all services together</p><p><strong>Structure:</strong></p><p>yaml</p><pre>version: &#39;3.8&#39;<br>services:<br>  # Database for user-service<br>  user-db:<br>    image: postgres:15-alpine<br>    ports:<br>      - &quot;5432:5432&quot;<br>    environment:<br>      POSTGRES_DB: userdb<br>  <br>  # user-service application<br>  user-service:<br>    build: ./user-service<br>    ports:<br>      - &quot;8081:8081&quot;<br>    environment:<br>      DB_HOST: user-db        # Service name, resolved by Docker<br>      DB_PORT: 5432<br>      DB_NAME: userdb<br>    depends_on:<br>      user-db:<br>        condition: service_healthy<br>  <br>  # Same pattern for order-db, order-service, notification-db, notification-service</pre><h3>Key Concepts</h3><p><strong>1. Services</strong></p><p>yaml</p><pre>services:<br>  user-service:        # Service name (used for inter-service communication)<br>    image: ...         # Docker image to use<br>    build: ./...       # Or build from Dockerfile<br>    ports:             # Map ports: localhost:container<br>    environment:       # Environment variables<br>    depends_on:        # Wait for other services</pre><p><strong>2. Networks</strong></p><p>yaml</p><pre>networks:<br>  microservices-network:<br>    driver: bridge</pre><ul><li>Docker creates internal network</li><li>All services connected</li><li>Service names resolve to IPs</li><li>order-service can reach user-service by name</li></ul><p><strong>3. Volumes</strong></p><p>yaml</p><pre>volumes:<br>  user_db_data:<br>  order_db_data:<br>  notification_db_data:</pre><ul><li>Persist database data</li><li>Survives container restart</li><li>Each database has its own volume</li></ul><p><strong>4. Health Checks</strong></p><p>yaml</p><pre>user-db:<br>  healthcheck:<br>    test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U postgres&quot;]<br>    interval: 10s<br>    retries: 5<br>user-service:<br>  depends_on:<br>    user-db:<br>      condition: service_healthy</pre><ul><li>Wait for database to be ready before starting app</li><li>Prevents app startup errors</li></ul><h3>Ports in Docker Compose</h3><p><strong>Three levels of ports:</strong></p><ol><li><strong>Container internal port:</strong> What the service listens on inside container</li></ol><p>yaml</p><pre>user-service:<br>     ports:<br>       - &quot;8081:8081&quot;<br>         # ↑    ↑<br>         # |    └─ Container port (internal)<br>         # └────── Host port (your laptop)</pre><ol><li><strong>Service name resolution:</strong> How other services reach it</li></ol><p>java</p><pre>String url = &quot;http://user-service:8081&quot;;  // Service name resolves in Docker network</pre><ol><li><strong>Your laptop:</strong> How you access from terminal</li></ol><p>bash</p><pre>curl http://localhost:8081/users  # localhost = your machine</pre><h3>The Retry Pattern</h3><h3>Why Retry Logic?</h3><p><strong>Scenario:</strong> order-service calls user-service to validate user</p><p><strong>What if user-service is down?</strong></p><ul><li>First attempt: FAIL (connection refused)</li><li>Second attempt (after 1 second): FAIL</li><li>Third attempt (after 1 second): FAIL</li><li>After 3 failures: Give up, return error</li></ul><p><strong>Why retry?</strong></p><ul><li>Network hiccups (temporary failure)</li><li>Service restarting (brief unavailability)</li><li>Load spikes (service slow to respond)</li></ul><h3>Your Implementation</h3><p>java</p><pre>public boolean userExists(Long userId) {<br>    int maxRetries = 3;<br>    int retryCount = 0;<br>while (retryCount &lt; maxRetries) {<br>        try {<br>            // Attempt to call user-service<br>            String url = userServiceUrl + &quot;/users/&quot; + userId;<br>            Object response = restTemplate.getForObject(url, Object.class);<br>            return response != null;<br>            <br>        } catch (RestClientException e) {<br>            // Call failed<br>            retryCount++;<br>            <br>            if (retryCount &lt; maxRetries) {<br>                // Not last attempt, wait and retry<br>                System.out.println(&quot;Retrying... (&quot; + retryCount + &quot;/&quot; + maxRetries + &quot;)&quot;);<br>                Thread.sleep(1000);  // Wait 1 second<br>            } else {<br>                // Last attempt failed, give up<br>                System.out.println(&quot;User service unreachable after &quot; + maxRetries + &quot; retries&quot;);<br>                return false;<br>            }<br>        }<br>    }<br>    return false;<br>}</pre><h3>How It’s Used</h3><p><strong>In OrderController:</strong></p><p>java</p><pre>@PostMapping<br>public Object createOrder(@RequestBody Order order) {<br>    // Call with retry logic<br>    boolean userExists = userServiceClient.userExists(order.getUserId());<br>    <br>    if (!userExists) {<br>        return new ErrorResponse(&quot;User not found&quot;, <br>                                &quot;Cannot create order for non-existent user&quot;);<br>    }<br>    <br>    // User exists, create order<br>    return orderRepository.save(order);<br>}</pre><h3>Real-World Patterns (Future Learning)</h3><p><strong>Circuit Breaker:</strong> If service fails too often, stop calling it temporarily</p><pre>try call → fail → try again → fail → CIRCUIT OPEN (stop trying)</pre><p><strong>Timeout:</strong> Don’t wait forever for response</p><pre>request → 10 second wait → no response → timeout, retry<br>retry 1: wait 1 second<br>retry 2: wait 2 seconds<br>retry 3: wait 4 seconds</pre><p><strong>Exponential Backoff:</strong> Wait longer between retries</p><h3>Common Issues &amp; Solutions</h3><h3>Issue 1: Service Can’t Find Other Service</h3><p><strong>Error:</strong> Cannot resolve host: user-service</p><p><strong>Cause:</strong> Using wrong service name or service not on network</p><p><strong>Solution:</strong></p><p>yaml</p><pre># docker-compose.yml<br>services:<br>  user-service:          # ← Service name<br>    container_name: user-service<br>order-service:<br>    environment:<br>      USER_SERVICE_URL: http://user-service:8081  # ← Use service name</pre><h3>Issue 2: Port Already in Use</h3><p><strong>Error:</strong> ports are not available: ... address already in use</p><p><strong>Cause:</strong> Another service already listening on that port</p><p><strong>Solution:</strong></p><p>bash</p><pre># Find what&#39;s using the port<br>lsof -i :8082<br># Stop it<br>kill -9 &lt;PID&gt;<br># Or change docker-compose.yml ports</pre><h3>Issue 3: Database Connection Fails</h3><p><strong>Error:</strong> Connection refused from app to database</p><p><strong>Cause:</strong> App starting before database ready</p><p><strong>Solution:</strong></p><p>yaml</p><pre>order-service:<br>  depends_on:<br>    order-db:<br>      condition: service_healthy  # Wait for health check</pre><h3>Issue 4: Inter-Service Call Returns 404</h3><p><strong>Error:</strong> {&quot;error&quot;:&quot;User not found&quot;}</p><p><strong>Cause:</strong> User doesn’t exist, or wrong endpoint</p><p><strong>Solution:</strong></p><p>bash</p><pre># Test the endpoint directly<br>curl http://localhost:8081/users/1<br># Check spelling of URL<br># Check if service is running<br>docker compose ps</pre><h3>Issue 5: Services Can’t Communicate</h3><p><strong>Error:</strong> UserServiceClient gets timeout/connection refused</p><p><strong>Cause:</strong></p><ul><li>Service name wrong in URL</li><li>Service not started yet</li><li>Network not connected properly</li></ul><p><strong>Solution:</strong></p><p>bash</p><pre># Check if user-service is running<br>docker compose logs user-service<br># Test from order-service container<br>docker exec order-service curl http://user-service:8081/actuator/health<br># Check network<br>docker network ls<br>docker network inspect &lt;network-name</pre><h3>Key Concepts</h3><h3>Service Boundaries</h3><p><strong>What each service owns:</strong></p><ul><li>Its own business domain</li><li>Its own database</li><li>Its own REST endpoints</li><li>Its own code repository (in real projects)</li></ul><p><strong>What each service doesn’t own:</strong></p><ul><li>Other service’s data</li><li>Direct access to other databases</li><li>Internal implementation details of other services</li></ul><h3>Loose Coupling</h3><p><strong>Tight Coupling (Bad):</strong></p><pre>order-service directly queries user database<br>↓<br>Can&#39;t change user database schema without breaking order-service<br>Can&#39;t scale user database independently<br>Can&#39;t deploy user-service independentl</pre><p><strong>Loose Coupling (Good):</strong></p><pre>order-service calls user-service API<br>↓<br>Can change user implementation without breaking order-service<br>Can scale each independently<br>Can deploy each independently<br>Can even replace user-service with different implementation</pre><h3>Data Ownership</h3><p><strong>Each service owns its data:</strong></p><ul><li>user-service owns user data</li><li>order-service owns order data</li><li>notification-service owns notification data</li></ul><p><strong>No service owns another’s data:</strong></p><ul><li>order-service doesn’t copy user data</li><li>order-service doesn’t cache user data (for now)</li><li>order-service asks user-service when needed</li></ul><h3>Failure Modes</h3><p><strong>Monolith failure:</strong></p><pre>User service crashes<br>  ↓<br>Entire app crashes<br>  ↓<br>Orders, notifications, everything stops</pre><p><strong>Microservices failure:</strong></p><pre>User service crashes<br>  ↓<br>Order service still works (but can&#39;t validate users)<br>  ↓<br>Returns error when trying to create orders<br>  ↓<br>Notification service still works</pre><h3>Distributed System Challenges</h3><p>You’ve now experienced:</p><ul><li><strong>Network latency:</strong> HTTP calls are slower than method calls</li><li><strong>Failure modes:</strong> One service down affects dependent services</li><li><strong>Complexity:</strong> Need retry logic, error handling</li><li><strong>Data consistency:</strong> Each service has own database</li></ul><p><strong>This is what Phase 4 (Kubernetes) helps solve!</strong></p><h3>Architecture Diagrams</h3><h3>Before (Monolith — Phase 2)</h3><pre>┌─────────────────────────────────────┐<br>│   Order Management Monolith         │<br>│                                     │<br>│  ┌────────────────────────────────┐ │<br>│  │ Spring Boot Application         │ │<br>│  │                                 │ │<br>│  │  UserController   OrderController│ │<br>│  │  UserRepository   OrderRepository│ │<br>│  │  User Entity      Order Entity  │ │<br>│  └────────────────────────────────┘ │<br>│                 ↓                    │<br>│  ┌────────────────────────────────┐ │<br>│  │ PostgreSQL Database             │ │<br>│  │                                 │ │<br>│  │ users table                     │ │<br>│  │ orders table                    │ │<br>│  └────────────────────────────────┘ │<br>└─────────────────────────────────────┘</pre><h3>After (Microservices — Phase 3)</h3><pre>┌────────────────────────────────────────────────────────────┐<br>│           Docker Compose Network                           │<br>│                                                             │<br>│  ┌──────────────────────┐  ┌──────────────────────┐       │<br>│  │  user-service        │  │  user-db             │       │<br>│  │  (port 8081)         ├──┤  (port 5432)         │       │<br>│  │                      │  │  userdb              │       │<br>│  │  UserController      │  │  - users table       │       │<br>│  │  UserRepository      │  └──────────────────────┘       │<br>│  │  User Entity         │                                  │<br>│  └──────────────────────┘                                  │<br>│            ↑                                               │<br>│            │ HTTP calls                                    │<br>│            │ user-service:8081                             │<br>│            │                                               │<br>│  ┌──────────────────────┐  ┌──────────────────────┐       │<br>│  │  order-service       │  │  order-db            │       │<br>│  │  (port 8082)         ├──┤  (port 5433)         │       │<br>│  │                      │  │  orderdb             │       │<br>│  │  OrderController     │  │  - orders table      │       │<br>│  │  OrderRepository     │  └──────────────────────┘       │<br>│  │  UserServiceClient ◄─┐                                  │<br>│  │  Order Entity        │                                  │<br>│  └──────────────────────┘                                  │<br>│                                                             │<br>│  ┌──────────────────────┐  ┌──────────────────────┐       │<br>│  │ notification-service │  │ notification-db      │       │<br>│  │ (port 8083)          ├──┤ (port 5434)          │       │<br>│  │                      │  │ notificationdb       │       │<br>│  │ NotificationCtrl     │  │ - notifications tbl  │       │<br>│  │ NotificationRepo     │  └──────────────────────┘       │<br>│  │ NotificationService  │                                  │<br>│  │ Notification Entity  │                                  │<br>│  └──────────────────────┘                                  │<br>│                                                             │<br>└────────────────────────────────────────────────────────────┘</pre><h3>Request Flow: Create Order</h3><pre>1. Browser/Client<br>   │<br>   └─→ POST /orders (localhost:8082)<br>       │<br>       └─→ order-service receives request<br>           │<br>           ├─→ UserServiceClient.userExists(userId=1)<br>           │   │<br>           │   └─→ HTTP GET http://user-service:8081/users/1<br>           │       │<br>           │       └─→ user-service receives request<br>           │           │<br>           │           └─→ Query user-db for user<br>           │               │<br>           │               └─→ Returns: {&quot;id&quot;:1, &quot;name&quot;:&quot;John&quot;, ...}<br>           │       │<br>           │       └─→ HTTP response<br>           │<br>           ├─→ User exists? YES<br>           │<br>           ├─→ Create Order object<br>           │<br>           ├─→ Save to order-db<br>           │<br>           └─→ HTTP response: {&quot;id&quot;:1, &quot;userId&quot;:1, ...}<br>       │<br>       └─→ Browser receives response</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c92939f72e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phase 2: Containerize It — Complete Learning Notes]]></title>
            <link>https://medium.com/@dolapavan/phase-2-containerize-it-complete-learning-notes-5b64d9977344?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b64d9977344</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 17:41:52 GMT</pubDate>
            <atom:updated>2026-01-25T16:51:33.080Z</atom:updated>
            <content:encoded><![CDATA[<h3>Phase 2: Containerize It — Complete Learning Notes</h3><h3>The Big Picture</h3><p><strong>Goal:</strong> Take your working Spring Boot application and package it with PostgreSQL so anyone can run it with one command: docker compose up</p><p><strong>Why this matters:</strong></p><ul><li>Phase 1 worked on your laptop but failed on EC2 (Java version mismatch, environment differences)</li><li>Phase 2 solves this: everything is packaged together with exact versions</li><li>Reproducibility: Same setup runs on your laptop, your friend’s laptop, EC2, anywhere Docker is installed</li></ul><p><strong>The Journey:</strong></p><pre>Phase 1: Manual setup on EC2<br>↓<br>Phase 2: Containerized, reproducible everywhere<br>↓<br>Phase 3+: Orchestration, microservices, cloud</pre><h3>What Problem Does Docker Solve?</h3><h3>The Problem: “Works on My Machine”</h3><p><strong>Scenario 1 (Phase 1):</strong></p><ul><li>Your laptop: Java 21, Maven 3.9.12, macOS</li><li>EC2 instance: Java 17, Maven 3.9.12, Ubuntu 24.04</li><li>Result: Maven compiler fails because Java versions don’t match</li></ul><p><strong>Scenario 2:</strong></p><ul><li>You build an app</li><li>You give it to a teammate</li><li>They have a different Java version</li><li>App doesn’t work</li><li>Hours spent debugging environment issues instead of code</li></ul><p><strong>Scenario 3:</strong></p><ul><li>You deploy to AWS</li><li>6 months later, you need to deploy again</li><li>You forgot what Java version you used</li><li>You forgot what dependencies you installed</li><li>Deployment breaks</li></ul><h3>The Solution: Docker</h3><p><strong>Docker packages:</strong></p><ul><li>Your exact operating system (Linux)</li><li>Your exact Java version</li><li>Your exact dependencies</li><li>Your application code</li><li>All configuration</li></ul><p><strong>Result:</strong> Same environment everywhere</p><pre>Your laptop:     Java 21, Ubuntu → Works <br>Friend&#39;s laptop: Java 21, Ubuntu → Works <br>EC2:             Java 21, Ubuntu → Works </pre><p><strong>Key insight:</strong> Docker doesn’t change your app. It just guarantees the environment is identical everywhere.</p><h3>Docker Fundamentals</h3><h3>Three Key Concepts</h3><h3>1. Dockerfile</h3><p><strong>What it is:</strong> A recipe/blueprint for building a Docker image</p><p><strong>Analogy:</strong> Dockerfile is like a cooking recipe:</p><ul><li>Ingredient list (base image)</li><li>Step-by-step instructions (RUN, COPY, etc.)</li><li>Final result (a built environment)</li></ul><h3>2. Docker Image</h3><p><strong>What it is:</strong> The result of building a Dockerfile. A snapshot/blueprint of an environment.</p><p><strong>Analogy:</strong> Like a class definition in programming</p><ul><li>It’s a template</li><li>It’s immutable (doesn’t change)</li><li>You can create multiple copies from it</li><li>It contains: OS + Java + dependencies + code</li></ul><h3>3. Docker Container</h3><p><strong>What it is:</strong> A running instance of a Docker image.</p><p><strong>Analogy:</strong> Like an object/instance created from a class</p><ul><li>It’s a running process</li><li>It’s isolated (has its own filesystem, network, processes)</li><li>Multiple containers can run from same image</li><li>Each container is independent</li></ul><p><strong>The relationship:</strong></p><pre>Dockerfile (recipe)<br>    ↓<br>Docker Image (built blueprint, like 150MB file)<br>    ↓<br>Docker Container (running instance, like a mini-computer)</pre><h3>Building Your First Dockerfile</h3><h3>Simple Dockerfile (What You Started With)</h3><pre>FROM openjdk:17-jdk-slim</pre><pre>WORKDIR /app</pre><pre>COPY target/Order-Management-0.0.1-SNAPSHOT.jar app.jar</pre><pre>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p><strong>What each line does:</strong></p><p>Line Command Meaning 1 FROM openjdk:17-jdk-slim Start with Ubuntu + Java 17 (pre-built image from Docker Hub) 3 WORKDIR /app Create directory /app and make it current directory 5 COPY target/... app.jar Copy your .jar file from laptop into container at /app/app.jar 7 ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;] When container starts, run: java -jar app.jar</p><p><strong>Size:</strong> ~900MB (includes Java, OS, your app)</p><p><strong>Problem:</strong> You’re using a base image that includes Maven, build tools, etc. But when your app runs, it doesn’t need these. It’s bloat.</p><h3>Multi-Stage Dockerfile</h3><h3>The Concept</h3><p><strong>Problem we’re solving:</strong></p><ul><li>Stage 1: Build your app (needs Maven, compiler, build tools)</li><li>Stage 2: Run your app (only needs Java runtime)</li><li>Current approach: Stage 1 artifacts stay in final image (wasted space)</li></ul><p><strong>Solution: Multi-stage build</strong></p><pre>Stage 1 (builder): Maven image → Build .jar → Keep result<br>Stage 2 (runtime): Tiny Java image → Copy .jar from Stage 1 → Discard Stage 1<br>Final image: Only Stage 2 (much smaller)</pre><h3>Multi-Stage Dockerfile (What You Built)</h3><pre># Stage 1: Build stage<br>FROM maven:3.9-eclipse-temurin-21 AS builder</pre><pre>WORKDIR /app</pre><pre>COPY pom.xml .<br>COPY src ./src</pre><pre>RUN mvn clean package -DskipTests</pre><pre># Stage 2: Runtime stage<br>FROM maven:3.9-eclipse-temurin-21</pre><pre>WORKDIR /app</pre><pre>COPY --from=builder /app/target/Order-Management-0.0.1-SNAPSHOT.jar app.jar</pre><pre>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p><strong>What’s happening:</strong></p><p><strong>Stage 1 (builder):</strong></p><ul><li>Uses Maven image (has Java + Maven + compiler)</li><li>Copies your source code</li><li>Runs mvn clean package to BUILD the .jar</li><li>Result: /app/target/Order-Management-0.0.1-SNAPSHOT.jar exists</li></ul><p><strong>Stage 2 (runtime):</strong></p><ul><li>Uses a smaller Java image</li><li>Copies ONLY the .jar from Stage 1</li><li>Doesn’t need source code, doesn’t need Maven</li><li>When container runs, just executes java -jar app.jar</li></ul><p><strong>The magic:</strong> Docker throws away Stage 1 after copying the .jar. You only get Stage 2.</p><p><strong>Size benefit:</strong></p><ul><li>Before: ~930MB (includes Maven, compiler, source code)</li><li>After: ~400MB (only Java runtime + your app)</li><li>Savings: ~60%</li></ul><p><strong>Real-world production benefit:</strong></p><ul><li>Faster deployment (smaller image to download)</li><li>Smaller attack surface (fewer tools = fewer vulnerabilities)</li><li>Cleaner environment (only what you need to run)</li></ul><h3>Common Multi-Stage Patterns</h3><p><strong>Pattern 1: Builder + Runtime (what you used)</strong></p><pre>FROM maven:3.9 AS builder<br># ... build steps ...</pre><pre>FROM eclipse-temurin:21-jre<br># ... copy only .jar ...</pre><p><strong>Pattern 2: Builder + Minified Runtime</strong></p><pre>FROM maven:3.9 AS builder<br># ... build steps ...</pre><pre>FROM eclipse-temurin:21-jre-alpine  # Alpine = tiny Linux<br># ... copy only .jar ...</pre><p>(Alpine reduces image from 400MB to ~200MB)</p><h3>Docker Compose</h3><h3>The Problem It Solves</h3><p><strong>Phase 1 experience:</strong> You had to manually manage:</p><ul><li>EC2 instance for app</li><li>Nginx configuration</li><li>Environment variables</li><li>Database setup</li><li>Network configuration</li></ul><p><strong>If you had multiple services, it was chaos.</strong></p><p><strong>Docker Compose solves this:</strong> Define multiple services in ONE file, start all with ONE command.</p><h3>Your Docker Compose File</h3><pre>version: &#39;3.8&#39;</pre><pre>services:<br>  postgres:<br>    image: postgres:15-alpine<br>    container_name: order-db<br>    environment:<br>      POSTGRES_DB: orderdb<br>      POSTGRES_USER: dola<br>      POSTGRES_PASSWORD: dola123<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U dola&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 5</pre><pre>  app:<br>    build: .<br>    container_name: order-app<br>    environment:<br>      DB_HOST: postgres<br>      DB_PORT: 5432<br>      DB_NAME: orderdb<br>      DB_USER: dola<br>      DB_PASSWORD: dola123<br>    ports:<br>      - &quot;8080:8080&quot;<br>    depends_on:<br>      postgres:<br>        condition: service_healthy<br>    restart: on-failure</pre><pre>volumes:<br>  postgres_data:</pre><h3>Understanding Each Section</h3><h3>services (the main part)</h3><p><strong>postgres service:</strong></p><pre>postgres:<br>  image: postgres:15-alpine          # Use pre-built PostgreSQL image<br>  container_name: order-db           # Name this container &quot;order-db&quot;<br>  environment:                       # Environment variables inside container<br>    POSTGRES_DB: orderdb             # Create database named &quot;orderdb&quot;<br>    POSTGRES_USER: dola              # Create user named &quot;dola&quot;<br>    POSTGRES_PASSWORD: dola123       # With password &quot;dola123&quot;<br>  ports:<br>    - &quot;5432:5432&quot;                    # Map container port 5432 → laptop port 5432<br>  volumes:<br>    - postgres_data:/var/lib/postgresql/data  # Persist data even if container stops<br>  healthcheck:                       # Check if service is healthy<br>    test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U dola&quot;]<br>    interval: 10s<br>    timeout: 5s<br>    retries: 5</pre><p><strong>app service:</strong></p><pre>app:<br>  build: .                           # Build using Dockerfile in current directory<br>  container_name: order-app          # Name this container &quot;order-app&quot;<br>  environment:                       # Pass these to Spring Boot app<br>    DB_HOST: postgres                # ← Service name! Docker&#39;s magic<br>    DB_PORT: 5432<br>    DB_NAME: orderdb<br>    DB_USER: dola<br>    DB_PASSWORD: dola123<br>  ports:<br>    - &quot;8080:8080&quot;                    # Map container port 8080 → laptop port 8080<br>  depends_on:<br>    postgres:<br>      condition: service_healthy     # Wait for postgres to be healthy before starting app<br>  restart: on-failure                # If app crashes, restart it</pre><h3>volumes (for persistence)</h3><pre>volumes:<br>  postgres_data:                     # Define a volume named &quot;postgres_data&quot;</pre><p>This persists PostgreSQL data so it survives container restarts.</p><h3>How Services Communicate</h3><p><strong>The Magic:</strong> DB_HOST: postgres</p><p>In your Docker Compose file, you name the PostgreSQL service postgres. Inside Docker Compose&#39;s network:</p><ul><li>Your app can reach PostgreSQL by hostname: postgres</li><li>Docker automatically resolves postgres → PostgreSQL container&#39;s IP</li><li>Your app connects to: jdbc:postgresql://postgres:5432/orderdb</li></ul><p><strong>Why this works:</strong></p><ul><li>Docker Compose creates a virtual network</li><li>All services join this network</li><li>Services can reach each other by name (like DNS)</li></ul><h3>Spring Boot + PostgreSQL Integration</h3><h3>The Configuration</h3><h3>In application.properties</h3><p><strong>Before (H2):</strong></p><pre># H2 is in-memory, auto-configures, no setup needed<br>spring.application.name=Order-Management</pre><p><strong>After (PostgreSQL):</strong></p><pre>spring.application.name=Order-Management<br># Database Connection<br>spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:orderdb}<br>spring.datasource.username=${DB_USER:postgres}<br>spring.datasource.password=${DB_PASSWORD:postgres}<br>spring.datasource.driver-class-name=org.postgresql.Driver<br># JPA Configuration<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect<br>spring.jpa.show-sql=false</pre><p><strong>Understanding the syntax:</strong></p><pre>${DB_HOST:localhost}<br> ↑       ↑<br> |       └─── Default value if env var not set<br> └─────────── Read from environment variable</pre><p><strong>When running locally (defaults):</strong></p><pre>DB_HOST defaults to: localhost<br>DB_PORT defaults to: 5432<br>DB_NAME defaults to: orderdb</pre><p><strong>When running in Docker Compose (overrides):</strong></p><pre>environment:<br>  DB_HOST: postgres      # ← Overrides the default &quot;localhost&quot;<br>  DB_PORT: 5432<br>  DB_NAME: orderdb<br>  DB_USER: dola<br>  DB_PASSWORD: dola123</pre><h3>In pom.xml</h3><p><strong>Add PostgreSQL driver dependency:</strong></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.postgresql&lt;/groupId&gt;<br>    &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>    &lt;version&gt;42.7.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>This lets Spring Boot talk to PostgreSQL (JDBC driver).</p><h3>Key Differences: H2 vs PostgreSQL</h3><p>Aspect H2 PostgreSQL <strong>Storage</strong> Memory (RAM) Disk <strong>Data persistence</strong> Lost on restart Survives restart <strong>Setup</strong> Zero config Needs host, port, credentials <strong>Use case</strong> Testing, learning Production <strong>Performance</strong> Fast (no network) Slightly slower (network I/O)</p><h3>Health Endpoints with Actuator</h3><h3>Why Health Endpoints?</h3><p><strong>Problem:</strong> How does Docker know if your app is healthy?</p><ul><li>Is it running?</li><li>Can it reach the database?</li><li>Is it ready to handle requests?</li></ul><p><strong>Solution:</strong> Spring Boot Actuator provides /actuator/health endpoint</p><h3>Adding Actuator</h3><p><strong>In </strong><strong>pom.xml:</strong></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>In </strong><strong>application.properties (optional, but recommended):</strong></p><pre>management.endpoints.web.exposure.include=health<br>management.endpoint.health.show-details=always</pre><h3>Using the Health Endpoint</h3><p><strong>Test it:</strong></p><pre>curl &lt;http://localhost:8080/actuator/health&gt;</pre><p><strong>Response:</strong></p><pre>{<br>  &quot;status&quot;: &quot;UP&quot;,<br>  &quot;groups&quot;: [&quot;liveness&quot;, &quot;readiness&quot;]<br>}</pre><p><strong>What it tells you:</strong></p><ul><li>status: UP = App is running and healthy</li><li>If database disconnected: status: DOWN</li><li>Docker Compose uses this to detect if service is ready</li></ul><h3>Common Issues &amp; Solutions</h3><h3>Issue 1: “database ‘X’ does not exist”</h3><p><strong>Cause:</strong> App trying to connect to wrong database name</p><p><strong>Debug steps:</strong></p><ol><li>Check application.properties - what&#39;s the database name?</li><li>Check docker-compose.yml - what&#39;s POSTGRES_DB?</li><li>Check environment in app service - what&#39;s DB_NAME?</li></ol><p><strong>Solution:</strong> Make sure all three match</p><p><strong>Example fix:</strong></p><pre># application.properties<br>spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:orderdb}</pre><pre># docker-compose.yml<br>environment:<br>  POSTGRES_DB: orderdb     # ← Must match<br>  DB_NAME: orderdb         # ← Must match</pre><h3>Issue 2: “Connection refused”</h3><p><strong>Cause:</strong> App trying to connect to database before it’s ready</p><p><strong>Solution:</strong> Use depends_on with service_healthy condition</p><pre>app:<br>  depends_on:<br>    postgres:<br>      condition: service_healthy</pre><h3>Issue 3: “Class file version X not supported”</h3><p><strong>Cause:</strong> .jar compiled with Java 21, but Docker image only has Java 17</p><p><strong>Solution:</strong> Match Java versions</p><pre>FROM eclipse-temurin:21-jdk-slim  # ← Use Java 21 if jar was compiled with Java 21</pre><h3>Issue 4: Containers won’t stop with Ctrl+C</h3><p><strong>Cause:</strong> Normal Docker Compose behavior</p><p><strong>Solution:</strong> Use separate terminal for logs, or use flags</p><pre># In one terminal<br>docker compose up</pre><pre># In another terminal when you want to stop<br>docker compose down</pre><h3>Issue 5: Data disappears after restart</h3><p><strong>Cause:</strong> Volume not properly configured</p><p><strong>Check your volumes:</strong></p><pre>volumes:<br>  postgres_data:  # ← Must be defined</pre><pre>services:<br>  postgres:<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data  # ← Must use the volume</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b64d9977344" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phase 1: Monolith on EC2 — Complete Learning Notes]]></title>
            <link>https://medium.com/@dolapavan/phase-1-monolith-on-ec2-complete-learning-notes-9bb69a4eb815?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bb69a4eb815</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 00:19:29 GMT</pubDate>
            <atom:updated>2026-01-25T16:52:00.791Z</atom:updated>
            <content:encoded><![CDATA[<h3>Phase 1: Monolith on EC2 — Complete Learning Notes</h3><h3>The Big Picture</h3><p><strong>Goal:</strong> Deploy a Spring Boot REST API on a real cloud server (AWS EC2) and make it accessible to the internet through a reverse proxy (Nginx).</p><p><strong>Why this matters:</strong></p><ul><li>You moved from local development (localhost:8080) to cloud deployment</li><li>You learned how real applications are structured in production</li><li>You understand the infrastructure layer that sits between your code and users</li></ul><h3>Architecture &amp; Components</h3><h3>Components Used:</h3><pre>┌─────────────────┐<br>│   Your Laptop   │<br>│  (Client/User)  │<br>└────────┬────────┘<br>         │ curl request to port 80<br>         │ &lt;http://3.128.199.90/users/1&gt;<br>         │<br>    ┌────▼────────────────────────────┐<br>    │     AWS EC2 Instance (Ubuntu)    │<br>    │     Public IP: 3.128.199.90      │<br>    │                                   │<br>    │  ┌──────────────────────────────┐│<br>    │  │ Nginx (Reverse Proxy)         ││<br>    │  │ Listens on: Port 80           ││<br>    │  │ Forwards to: localhost:8080   ││<br>    │  └────────┬─────────────────────┘│<br>    │           │ internal request      │<br>    │           │                       │<br>    │  ┌────────▼──────────────────────┐│<br>    │  │ Spring Boot Application       ││<br>    │  │ Listens on: Port 8080 (local)││<br>    │  │ Has: User &amp; Order endpoints   ││<br>    │  └────────┬─────────────────────┘│<br>    │           │                       │<br>    │  ┌────────▼──────────────────────┐│<br>    │  │ H2 In-Memory Database         ││<br>    │  │ Stores: Users &amp; Orders        ││<br>    │  └──────────────────────────────┘│<br>    └────────────────────────────────────┘</pre><h3>Why This Architecture?</h3><p><strong>Before (Local Development):</strong></p><pre>You → localhost:8080 → Spring Boot → H2 Database</pre><p>Problem: Only works on your machine. Not scalable.</p><p><strong>After (Cloud Deployment):</strong></p><pre>Internet Users → Port 80 (Public) → Nginx (Gatekeeper) → Port 8080 (Hidden) → Spring Boot → H2 Database</pre><p>Benefits:</p><ul><li>Anyone on internet can access</li><li>Nginx handles routing, security, caching</li><li>Spring Boot doesn’t expose port 8080 directly</li><li>Separation of concerns (reverse proxy vs application)</li></ul><h3>What You Built</h3><h3>1. Spring Boot REST API</h3><p><strong>Entities:</strong></p><ul><li>User - name, email, auto-generated ID</li><li>Order - product_name, product_price, total, order_date, status, user_id, auto-generated ID</li></ul><p><strong>Endpoints:</strong></p><pre>POST   /users          → Create a user<br>GET    /users/{id}     → Get a user by ID<br>POST   /orders         → Create an order<br>GET    /orders/{id}    → Get an order by ID</pre><p><strong>Technology Stack:</strong></p><ul><li>Spring Boot 3.x (REST framework)</li><li>Spring Data JPA (database abstraction)</li><li>Jakarta Persistence (entity annotations)</li><li>H2 Database (in-memory, for learning)</li><li>Maven (build tool)</li><li>Java 17/21 (runtime)</li></ul><h3>2. Nginx Configuration</h3><p><strong>Role:</strong> Reverse proxy (sits in front of your app)</p><p><strong>Configuration (simplified):</strong></p><pre>server {<br>    listen 80;  # Listen on HTTP port<br>location / {<br>        proxy_pass &lt;http://localhost:8080&gt;;  # Forward to Spring Boot<br>        # Pass important headers to Spring Boot<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><p><strong>What those headers do:</strong></p><ul><li>Host - tells Spring Boot what domain was requested</li><li>X-Real-IP - the user&#39;s actual IP address</li><li>X-Forwarded-For - same as above (redundant but safe)</li><li>X-Forwarded-Proto - whether request was HTTP or HTTPS</li></ul><h3>3. AWS EC2 Instance</h3><p><strong>Configuration:</strong></p><ul><li>Instance Type: t2.micro (free tier eligible)</li><li>Operating System: Ubuntu 24.04 LTS</li><li>Region: US (your IP determines availability zone)</li><li>Security Group: Custom rules for SSH, HTTP, HTTPS</li><li>Key Pair: .pem file for SSH authentication</li></ul><h3>Step-by-Step Walkthrough</h3><h3>Phase 1a: Local Development (Your Laptop)</h3><p><strong>Step 1: Create Spring Boot Project</strong></p><pre># Using Spring Initializr (start.spring.io)<br># Dependencies: Spring Web, Spring Data JPA, H2 Database</pre><p><strong>Step 2: Create Entity Classes</strong></p><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>public class User {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.AUTO)<br>    private Long id;<br>    private String name;<br>    private String email;<br>    // getters/setters<br>}</pre><pre>@Entity<br>@Table(name = &quot;orders&quot;)<br>public class Order {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.AUTO)<br>    private Long id;<br>    private Long userId;<br>    private String productName;<br>    private Double productPrice;<br>    private Double total;<br>    private LocalDateTime orderDate;<br>    private String status;<br>    // getters/setters<br>}</pre><p><strong>Why </strong><strong>@Table annotation?</strong></p><ul><li>order is a SQL reserved keyword</li><li>@Table(name = &quot;orders&quot;) tells Hibernate to use a different table name</li><li>Without this, Maven build fails</li></ul><p><strong>Step 3: Create Repositories</strong></p><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {}<br>public interface OrderRepository extends JpaRepository&lt;Order, Long&gt; {}</pre><p><strong>Why JpaRepository?</strong></p><ul><li>Automatically gives you save(), findById(), delete(), etc.</li><li>No need to write SQL queries manually</li><li>Spring handles database operations for you</li></ul><p><strong>Step 4: Create Controllers</strong></p><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br>    @Autowired<br>    private UserRepository userRepository;</pre><pre>    @PostMapping<br>    public User createUser(@RequestBody User user) {<br>        return userRepository.save(user);<br>    }</pre><pre>    @GetMapping(&quot;/{id}&quot;)<br>    public User getUser(@PathVariable Long id) {<br>        return userRepository.findById(id)<br>            .orElseThrow(() -&gt; new RuntimeException(&quot;User not found&quot;));<br>    }<br>}</pre><p><strong>Step 5: Test Locally</strong></p><pre>mvn spring-boot:run</pre><pre># In another terminal:<br>curl -X POST &lt;http://localhost:8080/users&gt; \\<br>  -H &quot;Content-Type: application/json&quot; \\<br>  -d &#39;{&quot;name&quot;:&quot;John&quot;,&quot;email&quot;:&quot;john@example.com&quot;}&#39;</pre><pre>curl &lt;http://localhost:8080/users/1&gt;</pre><h3>Phase 1b: AWS Setup</h3><p><strong>Step 1: Create AWS Free Tier Account</strong></p><ul><li>Go to <a href="https://aws.amazon.com/free">https://aws.amazon.com/free</a></li><li>Sign up with email and payment method</li><li>Note: Free tier = $0 charges if you stay within limits</li></ul><p><strong>Step 2: Create EC2 Instance</strong></p><ul><li>AWS Console → EC2 → Launch Instance</li><li>Choose: Ubuntu 24.04 LTS, t2.micro</li><li>Create security group with rules:</li><li>SSH (port 22): Your IP only</li><li>HTTP (port 80): Anywhere (0.0.0.0/0)</li><li>Custom TCP (port 8080): Anywhere (0.0.0.0/0)</li><li>Create/download key pair (.pem file)</li></ul><p><strong>Why these security rules?</strong></p><ul><li>SSH (port 22): Only you should manage the server</li><li>HTTP (port 80): Anyone can access your app</li><li>Port 8080: Direct access to app (temporary, for testing)</li></ul><p><strong>Step 3: Connect to EC2</strong></p><pre># Make key file readable only by you<br>chmod 600 /path/to/order-platform-key.pem</pre><pre># SSH in<br>ssh -i /path/to/order-platform-key.pem ubuntu@&lt;EC2-PUBLIC-IP&gt;</pre><p><strong>Step 4: Install Java</strong></p><pre>sudo apt-get update<br>sudo apt-get install openjdk-17-jdk-headless -y</pre><pre>java -version  # Verify installation</pre><p><strong>Step 5: Get Your Code on the Server</strong></p><pre># Option A: Clone from GitHub<br>git clone &lt;https://github.com/YOUR-USERNAME/order-management.git&gt;<br>cd order-management</pre><pre># Option B: Copy .jar file via scp<br>scp -i key.pem local-jar-path ubuntu@EC2-IP:/home/ubuntu/</pre><p><strong>Step 6: Build the Application</strong></p><pre># If you cloned source code:<br>mvn clean package</pre><pre># If you copied .jar file:<br># Already built, just need to run it</pre><p><strong>Step 7: Run Spring Boot App</strong></p><pre>java -jar Order-Management-0.0.1-SNAPSHOT.jar</pre><pre># Should see: &quot;Started OrderManagementApplication in X seconds&quot;</pre><h3>Phase 1c: Nginx Reverse Proxy Setup</h3><p><strong>Step 1: Install Nginx</strong></p><pre>sudo apt-get install nginx -y</pre><p><strong>Step 2: Configure Nginx</strong></p><pre>sudo nano /etc/nginx/sites-available/default</pre><pre># Replace with:<br>server {<br>    listen 80 default_server;<br>    listen [::]:80 default_server;<br>    server_name _;</pre><pre>    location / {<br>        proxy_pass &lt;http://localhost:8080&gt;;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><p><strong>Step 3: Reload Nginx</strong></p><pre># Important! Config changes don&#39;t apply until you reload<br>sudo systemctl reload nginx</pre><pre># Or restart (also works):<br>sudo systemctl restart nginx</pre><pre># Check status:<br>sudo systemctl status nginx</pre><p><strong>Step 4: Test from Your Laptop</strong></p><pre># Direct to app (port 8080):<br>curl &lt;http://EC2-IP:8080/users/1&gt;</pre><pre># Through Nginx (port 80):<br>curl &lt;http://EC2-IP/users/1&gt;</pre><pre># Both should return the same data</pre><h3>Key Concepts You Learned</h3><h3>1. Localhost vs Remote IP</h3><p><strong>localhost (127.0.0.1)</strong></p><ul><li>Special address meaning “this machine”</li><li>Only accessible from that machine</li><li>Used during development</li><li>Example: <a href="http://localhost:8080/">http://localhost:8080</a></li></ul><p><strong>Public IP Address</strong></p><ul><li>Assigned by cloud provider (AWS)</li><li>Accessible from anywhere on internet</li><li>Used in production</li><li>Example: <a href="http://3.128.199.90/">http://3.128.199.90</a></li></ul><p><strong>Private IP Address</strong></p><ul><li>Used within your VPC (Virtual Private Cloud)</li><li>Not accessible from internet</li><li>Nginx uses this internally: localhost:8080</li></ul><h3>2. Ports and Their Meanings</h3><pre>Port 22   - SSH (for managing servers)<br>Port 80   - HTTP (standard web traffic)<br>Port 443  - HTTPS (encrypted web traffic)<br>Port 8080 - Common alternative for development/internal apps</pre><p><strong>Why port 8080 for Spring Boot?</strong></p><ul><li>Port 1–1024 require root/admin privileges</li><li>8080 is unprivileged, so Spring Boot can start it easily</li><li>It’s not “exposed” to internet in our setup</li></ul><p><strong>Why port 80 for Nginx?</strong></p><ul><li>Standard HTTP port (what browsers default to)</li><li>Users can visit http://example.com without specifying port</li><li>Nginx runs as root/sudo, so it can bind to privileged ports</li></ul><h3>3. Reverse Proxy (Nginx) vs Forward Proxy</h3><p><strong>Forward Proxy</strong> (not what you built):</p><pre>Your Laptop → Proxy → Internet → Facebook<br>(Proxy is on your side, helps you reach the internet)</pre><p><strong>Reverse Proxy</strong> (what you built):</p><pre>Internet → Nginx (on server side) → Spring Boot App<br>(Proxy is on server side, helps route incoming requests)</pre><h3>4. Security Groups as Firewalls</h3><p>Think of security groups as AWS’s way of controlling traffic:</p><pre>All Traffic from Internet<br>         ↓<br>    Firewall (Security Group)<br>    Rule 1: Allow port 80 from 0.0.0.0/0 <br>    Rule 2: Allow port 22 from 76.136.91.252/32 <br>    Rule 3: Allow port 8080 from 0.0.0.0/0 <br>         ↓<br>    Allowed Traffic Reaches EC2</pre><p><strong>Your IP address matters:</strong></p><ul><li>When you SSH, security group checks: “Is this IP in my allowed list?”</li><li>If not, connection is blocked at the firewall level</li><li>If you change WiFi, your IP changes, and SSH might fail</li></ul><h3>5. In-Memory Database (H2) vs Persistent Database</h3><p><strong>H2 (what you’re using):</strong></p><ul><li>Data lives in RAM</li><li>Fast for testing</li><li><strong>Data is lost when app restarts</strong></li><li>Good for Phase 1 learning</li></ul><p><strong>PostgreSQL/MySQL (real production):</strong></p><ul><li>Data lives on disk</li><li>Survives restarts</li><li>Slower than memory but reliable</li><li>What you’ll use in Phase 2</li></ul><h3>6. Maven: Building Your App</h3><p><strong>mvn clean package does:</strong></p><ol><li>clean - Delete old build files (target/ folder)</li><li>compile - Turn .java files into .class files</li><li>package - Bundle everything into a .jar file</li></ol><p><strong>Result:</strong> A single executable .jar file with:</p><ul><li>Your code</li><li>All dependencies (Spring, JPA, etc.)</li><li>Embedded Tomcat web server</li><li>Ready to run on any machine with Java</li></ul><h3>7. JPA &amp; Hibernate Magic</h3><p>When you write:</p><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {}</pre><p><strong>Spring automatically creates:</strong></p><pre>// All these methods for free!<br>userRepository.save(user);           // INSERT<br>userRepository.findById(1L);         // SELECT by ID<br>userRepository.findAll();            // SELECT all<br>userRepository.delete(user);         // DELETE<br>userRepository.deleteById(1L);       // DELETE by ID<br>// ... and many more</pre><p>No SQL queries needed. Hibernate converts your code to SQL.</p><h3>Challenges &amp; Solutions</h3><h3>Challenge 1: .pem File Permissions</h3><p><strong>Error:</strong> Permissions 0644 for &#39;key.pem&#39; are too open</p><p><strong>Why:</strong> SSH won’t trust a key that “anyone can read”</p><p><strong>Solution:</strong></p><pre>chmod 600 key.pem  # Make readable only by you</pre><p><strong>Learning:</strong> Security is about trust. If your private key is readable by others, it’s not private anymore.</p><h3>Challenge 2: Maven Compilation Fails (Java Version Mismatch)</h3><p><strong>Error:</strong> error: release version 21 not supported</p><p><strong>Why:</strong> Your laptop has Java 21, but EC2 had Java 21 + Maven compiler plugin version mismatch</p><p><strong>Solution:</strong></p><ul><li>Built the .jar on your laptop (where it works)</li><li>Copied the .jar to EC2</li><li>Ran it with available Java version</li></ul><p><strong>Learning:</strong> Different environments can have different tool versions. Sometimes you work around it by doing compilation in a known-good environment.</p><h3>Challenge 3: IP Address Changed</h3><p><strong>Error:</strong> ssh: connect to host 3.145.17.152: Operation timed out</p><p><strong>Why:</strong> AWS reassigned your EC2 instance’s public IP when it restarted</p><p><strong>Solution:</strong> Check AWS Console for new IP, update SSH command</p><p><strong>Learning:</strong> In production, use Elastic IP (static IP) to avoid this. For free tier, just note the dynamic IP.</p><h3>Challenge 4: Security Group Blocked SSH</h3><p><strong>Error:</strong> Operation timed out even though instance is running</p><p><strong>Why:</strong> Your ISP assigned you a new IP, but security group only allowed your old IP</p><p><strong>Solution:</strong> Update security group rule to allow new IP</p><p><strong>Learning:</strong> Security groups are stateless firewalls. They block at network level, so SSH never even reaches the EC2 instance if IP isn’t whitelisted.</p><h3>Challenge 5: Nginx Returns 404, App is Running</h3><p><strong>Error:</strong></p><ul><li>Direct to app works: curl &lt;http://IP:8080/users/1&gt;</li><li>Through Nginx fails: curl &lt;http://IP/users/1&gt; (404 from Nginx)</li></ul><p><strong>Why:</strong> Config changes don’t auto-apply. Nginx was still using old config in memory.</p><p><strong>Solution:</strong></p><pre>sudo systemctl reload nginx</pre><p><strong>Learning:</strong> When you change configuration files, you must reload/restart the service for changes to take effect. This applies to all services (Nginx, Apache, PostgreSQL, etc.).</p><h3>Challenge 6: H2 Data Disappears After Restart</h3><p><strong>Error:</strong> Created user with ID 1, then restarted EC2. User is gone.</p><p><strong>Why:</strong> H2 is in-memory. When app stops, all data in RAM is lost.</p><p><strong>Solution:</strong> Recreate data after restart (temporary for Phase 1)</p><p><strong>Learning:</strong> This is why Phase 2 will use persistent database (PostgreSQL). You can’t lose user data in production.</p><h3>The Complete Request Journey</h3><h3>Request: curl &lt;http://3.128.199.90/users/1&gt;</h3><p><strong>Step 1: Your Laptop Makes Request</strong></p><pre>Your curl command creates HTTP request:<br>GET /users/1 HTTP/1.1<br>Host: 3.128.199.90<br>...</pre><p><strong>Step 2: Request Travels to AWS</strong></p><pre>Your ISP → Internet Backbone → AWS Data Center (Virginia)<br>↓<br>Reaches EC2 instance at public IP 3.128.199.90<br>↓<br>Hits Security Group Firewall<br>Rule: &quot;Allow port 80 from 0.0.0.0/0&quot; <br>→ Traffic allowed through</pre><p><strong>Step 3: Nginx Receives Request</strong></p><pre>Nginx on EC2 receives: GET /users/1<br>Nginx checks its config:<br>  &quot;location / { proxy_pass &lt;http://localhost:8080&gt;; }&quot;<br>→ &quot;I need to forward this to localhost:8080&quot;</pre><p><strong>Step 4: Nginx Adds Headers</strong></p><pre>Nginx adds:<br>  Host: 3.128.199.90 (original host)<br>  X-Real-IP: 76.136.91.252 (your public IP)<br>  X-Forwarded-For: 76.136.91.252<br>  X-Forwarded-Proto: http</pre><pre>This tells Spring Boot: &quot;This came from the internet, original host was 3.128.199.90&quot;</pre><p><strong>Step 5: Nginx Forwards to Spring Boot</strong></p><pre>Nginx sends modified request to localhost:8080:<br>GET /users/1 HTTP/1.1<br>Host: 3.128.199.90<br>X-Real-IP: 76.136.91.252<br>...</pre><p><strong>Step 6: Spring Boot Processes</strong></p><pre>Spring Boot receives request on port 8080<br>UserController.getUser(1) is called<br>↓<br>userRepository.findById(1L) queries H2 database<br>↓<br>H2 returns: User(id=1, name=John, email=john@example.com)<br>↓<br>Spring converts to JSON<br>↓<br>Spring returns HTTP response:<br>HTTP/1.1 200 OK<br>Content-Type: application/json<br>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;<br>}</pre><p><strong>Step 7: Nginx Forwards Response Back</strong></p><pre>Nginx receives response from Spring Boot<br>Nginx sends it back to your laptop</pre><p><strong>Step 8: Your Laptop Receives Response</strong></p><pre>curl displays:<br>{&quot;id&quot;:1,&quot;name&quot;:&quot;John&quot;,&quot;email&quot;:&quot;john@example.com&quot;}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bb69a4eb815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LRU Cache System — Complete Implementation Guide]]></title>
            <link>https://medium.com/@dolapavan/lru-cache-system-complete-implementation-guide-3e5e6bfbce5c?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5e6bfbce5c</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-thinking]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 02:16:40 GMT</pubDate>
            <atom:updated>2026-01-18T02:16:40.095Z</atom:updated>
            <content:encoded><![CDATA[<h3>LRU Cache System — Complete Implementation Guide</h3><h3>Overview</h3><p>A production-grade LRU (Least Recently Used) cache with TTL support, memory management, persistence, and thread-safety. This is what you’d find in systems like Redis, Memcached, or application-level caching.</p><h3>Architecture</h3><h3>Core Components</h3><h4>1. CacheEntry&lt;K, V&gt; — The Node</h4><pre>CacheEntry {<br>  - key: K                      // The cache key<br>  - value: V                    // The cached value<br>  - sizeInBytes: long          // Memory this entry uses<br>  - expirationTime: long       // When entry expires (for TTL)<br>  - lastAccessTime: long       // Timestamp of last access (for LRU)<br>  - accessFrequency: int       // How many times accessed (for future use)<br>  - prev: CacheEntry&lt;K, V&gt;    // Pointer to previous node (doubly linked list)<br>  - next: CacheEntry&lt;K, V&gt;    // Pointer to next node (doubly linked list)<br>}</pre><p><strong>Why each field?</strong></p><ul><li>sizeInBytes: Tracks actual memory usage instead of just counting entries</li><li>expirationTime: Enables automatic expiration (TTL feature)</li><li>lastAccessTime: Enables LRU eviction (which entries are least recently used?)</li><li>prev/next: Maintains order in linked list for O(1) access and manipulation</li></ul><h4>2. LRUCache&lt;K, V&gt; — The Cache Manager</h4><pre>LRUCache {<br>  - cache: HashMap&lt;K, CacheEntry&gt;      // O(1) lookup by key<br>  - head: CacheEntry                   // Most recently used entry<br>  - tail: CacheEntry                   // Least recently used entry<br>  - currentMemoryUsed: long            // Total memory in use<br>  - maxMemoryBytes: long               // Maximum allowed memory<br>  - lock: ReadWriteLock                // Thread-safety mechanism<br>  - persistenceFilePath: String        // Where to save/load cache<br>}</pre><h3>How It Works</h3><h3>1. Data Structure: HashMap + Doubly Linked List</h3><p><strong>Why this combination?</strong></p><pre>HashMap provides: O(1) lookup by key<br>  cache.get(&quot;user1&quot;) → instant access</pre><pre>Doubly Linked List provides: O(1) reordering<br>  When accessing &quot;user1&quot;, move it to front in O(1) time<br>  (just update 4 pointers, no array shifts)</pre><pre>Together they give us:<br>  - O(1) get<br>  - O(1) put<br>  - O(1) eviction<br>  - O(1) access tracking (move to front)</pre><p><strong>Visual representation:</strong></p><pre>Most Recent ←→ Least Recent<br>   head                      tail<br>    ↓                         ↓<br>[entry2] ← → [entry1] ← → [entry3]<br>    ↑                         ↑<br>   prev/next pointers</pre><p>When entry1 is accessed:</p><pre>Before: [entry2] ← → [entry1] ← → [entry3]<br>After:  [entry1] ← → [entry2] ← → [entry3]<br>        (just update 4 pointers in O(1) time!)</pre><h3>2. LRU Eviction: Which Entry to Remove?</h3><p>When cache is full and we need to add a new entry:</p><pre>1. Check if currentMemoryUsed + newSize &gt;= maxMemoryBytes<br>2. If yes, evict the TAIL (least recently used)<br>3. Keep evicting until there&#39;s space<br>4. Then add the new entry</pre><p><strong>Why evict LRU?</strong></p><ul><li>If someone hasn’t accessed an entry recently, they probably won’t soon</li><li>Keeping frequently accessed entries means fewer cache misses</li><li>Better hit rate = better performance</li></ul><h3>3. TTL: Automatic Expiration</h3><p>Each entry has expirationTime = System.currentTimeMillis() + ttlMillis</p><p><strong>Cleanup happens at two points:</strong></p><p><strong>Lazy Deletion</strong> (when accessed):</p><pre>public V get(K key) {<br>    entry = cache.get(key);<br>    if (entry.isExpired()) {<br>        remove it<br>        return null;<br>    }<br>    return entry.value;<br>}</pre><p><strong>Eager Deletion</strong> (when cache is 95% full):</p><pre>if (currentMemoryUsed &gt; maxMemoryBytes * 0.95) {<br>    cleanupExpiredEntries();  // Remove all expired entries<br>}</pre><p><strong>Why 95%?</strong></p><ul><li>Gives us buffer room before hitting max</li><li>Only triggers when pressure is high (not wasting CPU on frequent cleanups)</li><li>Allows recently expired entries to accumulate until needed</li></ul><h3>4. Memory Management: Tracking Bytes, Not Just Count</h3><p><strong>Traditional approach (BAD):</strong></p><pre>LRUCache&lt;String, String&gt; cache = new LRUCache&lt;&gt;(100);  // 100 entries<br>cache.put(&quot;small&quot;, &quot;x&quot;, 5000, ???);        // 1 byte value<br>cache.put(&quot;large&quot;, &quot;x&quot; * 1000000, 5000, ???); // 1MB value<br>// Both count as 1 entry - unfair!</pre><p><strong>Our approach (GOOD):</strong></p><pre>LRUCache&lt;String, String&gt; cache = new LRUCache&lt;&gt;(1_000_000);  // 1MB max<br>cache.put(&quot;small&quot;, &quot;x&quot;, 5000, 10);        // 10 bytes<br>cache.put(&quot;large&quot;, largeString, 5000, 1_000_000); // 1MB<br>// Actual memory usage is tracked accurately</pre><p><strong>How it works:</strong></p><pre>Every put() call:<br>  - Check if currentMemoryUsed + newSize &gt;= maxMemoryBytes<br>  - If yes, evict LRU entries until space available<br>  - Update currentMemoryUsed += newSize</pre><pre>Every eviction/removal:<br>  - currentMemoryUsed -= removedSize</pre><h3>5. Persistence: Save and Restore</h3><p><strong>On Shutdown:</strong></p><pre>cache.shutdown();  // Saves to disk, then clears memory</pre><p><strong>What gets saved?</strong></p><ul><li>Only non-expired entries</li><li>Format: key|value|remainingTTL|size (line by line)</li><li>Iterates from head to tail (most recent first)</li></ul><p><strong>On Startup:</strong></p><pre>LRUCache cache = new LRUCache&lt;&gt;(maxMemory, &quot;./cache.dat&quot;);<br>// Constructor automatically loads from disk</pre><p><strong>Why only non-expired entries?</strong></p><ul><li>No point saving entries that will be invalid anyway</li><li>Saves disk space</li><li>Cleaner data integrity</li></ul><p><strong>Persistence flow:</strong></p><pre>Startup:<br>  Create LRUCache with filepath<br>  → Constructor calls loadFromDisk()<br>  → Loads all saved entries back into memory<br>  → Cache is &quot;warm&quot; with previous data</pre><pre>Shutdown:<br>  Call cache.shutdown()<br>  → Calls saveToDisk()<br>  → Clears all memory<br>  → Prevents stale data on restart</pre><h3>6. Thread-Safety: ReadWriteLock</h3><p><strong>The Problem:</strong></p><pre>Thread 1: cache.put(&quot;key1&quot;, &quot;value1&quot;)  [writing]<br>Thread 2: cache.get(&quot;key2&quot;)             [reading]<br>Thread 3: cache.get(&quot;key3&quot;)             [reading]</pre><pre>Without locks:<br>- Thread 1 modifying linked list<br>- Thread 2 traversing linked list<br>- Thread 3 traversing linked list<br>→ CRASH! (concurrent modification)</pre><p><strong>The Solution: ReadWriteLock</strong></p><pre>private ReadWriteLock lock = new ReentrantReadWriteLock();</pre><pre>// For reads (multiple threads can read simultaneously):<br>lock.readLock().lock();<br>try {<br>    return cache.get(key);<br>} finally {<br>    lock.readLock().unlock();<br>}</pre><pre>// For writes (only one thread writes, blocks all reads):<br>lock.writeLock().lock();<br>try {<br>    cache.put(key, value);<br>} finally {<br>    lock.writeLock().unlock();<br>}</pre><p><strong>Why ReadWriteLock (not just synchronized)?</strong></p><pre>With synchronized (mutual exclusion):<br>  Thread 1: get() ← [LOCK]<br>  Thread 2: get() ← waiting... (blocked)<br>  Thread 3: get() ← waiting... (blocked)<br>  Performance: POOR (all threads wait for lock)</pre><pre>With ReadWriteLock:<br>  Thread 1: get() ← [READ LOCK]<br>  Thread 2: get() ← [READ LOCK]  (same lock, both can proceed!)<br>  Thread 3: get() ← [READ LOCK]  (same lock, both can proceed!)<br>  Performance: GOOD (multiple readers in parallel)<br>  <br>  If someone calls put():<br>  Thread 4: put() ← [WRITE LOCK]<br>  All readers blocked until writer is done</pre><p><strong>Lock Upgrade Problem:</strong> In get(), we have a special case:</p><pre>lock.readLock().lock();<br>// ... check if expired ...<br>if (entry.isExpired()) {<br>    lock.readLock().unlock();<br>    lock.writeLock().lock();  // Upgrade to write lock<br>    try {<br>        // Remove expired entry<br>    } finally {<br>        lock.writeLock().unlock();<br>        lock.readLock().lock();  // Downgrade back<br>    }<br>}</pre><p>This is a bit awkward because we can’t upgrade directly (deadlock risk), but it works!</p><p>Code Implementaion</p><pre>import java.io.*;<br>import java.util.*;<br>import java.util.concurrent.locks.ReadWriteLock;<br>import java.util.concurrent.locks.ReentrantReadWriteLock;<br><br>/**<br> * Thread-safe LRU Cache with TTL support, Memory Management, and Persistence<br> * <br> * Features:<br> * - LRU (Least Recently Used) eviction policy<br> * - TTL (Time-To-Live) with automatic expiration<br> * - Memory management (track bytes, not just count)<br> * - Automatic cleanup of expired entries at 95% capacity<br> * - Thread-safe operations with ReadWriteLock<br> * - Persistence to disk (save/load on shutdown/startup)<br> */<br>public class LRUCache&lt;K, V&gt; {<br>    private long maxMemoryBytes;<br>    private long currentMemoryUsed;<br>    private HashMap&lt;K, CacheEntry&lt;K, V&gt;&gt; cache;<br>    private CacheEntry&lt;K, V&gt; head;<br>    private CacheEntry&lt;K, V&gt; tail;<br>    private String persistenceFilePath;<br>    <br>    // Thread-safety: ReadWriteLock allows multiple readers, exclusive writer<br>    // Why ReadWriteLock? Multiple threads can read simultaneously, but writes are exclusive<br>    private ReadWriteLock lock = new ReentrantReadWriteLock();<br>    <br>    public LRUCache(long maxMemoryBytes) {<br>        this(maxMemoryBytes, null);<br>    }<br>    <br>    public LRUCache(long maxMemoryBytes, String persistenceFilePath) {<br>        this.maxMemoryBytes = maxMemoryBytes;<br>        this.currentMemoryUsed = 0;<br>        this.persistenceFilePath = persistenceFilePath;<br>        this.cache = new HashMap&lt;&gt;();<br>        this.head = null;<br>        this.tail = null;<br>        <br>        // Load cache from disk on startup if file exists<br>        if (persistenceFilePath != null) {<br>            loadFromDisk();<br>        }<br>    }<br>    <br>    /**<br>     * Get value from cache<br>     * Thread-safe: Uses read lock (multiple threads can read simultaneously)<br>     */<br>    public V get(K key) {<br>        lock.readLock().lock();<br>        try {<br>            if (!cache.containsKey(key)) {<br>                return null;<br>            }<br>            <br>            CacheEntry&lt;K, V&gt; entry = cache.get(key);<br>            <br>            // Check if expired<br>            if (entry.isExpired()) {<br>                lock.readLock().unlock();<br>                lock.writeLock().lock();<br>                try {<br>                    cache.remove(key);<br>                    removeNodeFromLinkedList(entry);<br>                    return null;<br>                } finally {<br>                    lock.writeLock().unlock();<br>                    lock.readLock().lock();<br>                }<br>            }<br>            <br>            // Move to front (mark as recently used)<br>            lock.readLock().unlock();<br>            lock.writeLock().lock();<br>            try {<br>                moveToFront(entry);<br>                return entry.value;<br>            } finally {<br>                lock.writeLock().unlock();<br>            }<br>        } finally {<br>            if (lock.readLock() != null) {<br>                try {<br>                    lock.readLock().unlock();<br>                } catch (Exception e) {<br>                    // Already unlocked<br>                }<br>            }<br>        }<br>    }<br>    <br>    /**<br>     * Put entry in cache with TTL and size<br>     * Thread-safe: Uses write lock (exclusive access)<br>     */<br>    public void put(K key, V value, long ttlMillis, long sizeInBytes) {<br>        lock.writeLock().lock();<br>        try {<br>            // Handle existing key - update value and TTL<br>            if (cache.containsKey(key)) {<br>                CacheEntry&lt;K, V&gt; entry = cache.get(key);<br>                <br>                // Subtract old size<br>                currentMemoryUsed -= entry.sizeInBytes;<br>                <br>                // Update entry<br>                entry.value = value;<br>                entry.sizeInBytes = sizeInBytes;<br>                entry.expirationTime = System.currentTimeMillis() + ttlMillis;<br>                entry.updateAccess();<br>                moveToFront(entry);<br>                <br>                // Add new size<br>                currentMemoryUsed += sizeInBytes;<br>            } else {<br>                // New entry - make space if necessary<br>                while (currentMemoryUsed + sizeInBytes &gt;= maxMemoryBytes) {<br>                    evictTail();<br>                }<br>                <br>                CacheEntry&lt;K, V&gt; newEntry = new CacheEntry&lt;&gt;(key, value, ttlMillis, sizeInBytes);<br>                addToFront(newEntry);<br>                cache.put(key, newEntry);<br>                currentMemoryUsed += sizeInBytes;<br>            }<br>            <br>            // Trigger cleanup if at 95% capacity (only remove expired entries)<br>            if (currentMemoryUsed &gt; maxMemoryBytes * 0.95) {<br>                cleanupExpiredEntries();<br>            }<br>        } finally {<br>            lock.writeLock().unlock();<br>        }<br>    }<br>    <br>    /**<br>     * Move entry to front of linked list (most recently used)<br>     * Called during access or update<br>     */<br>    private void moveToFront(CacheEntry&lt;K, V&gt; entry) {<br>        // Remove from current position<br>        if (entry.prev != null) {<br>            entry.prev.next = entry.next;<br>        }<br>        <br>        if (entry.next != null) {<br>            entry.next.prev = entry.prev;<br>        }<br>        <br>        // Update tail if entry was tail<br>        if (entry == tail) {<br>            tail = entry.prev;<br>        }<br>        <br>        // Add to front<br>        entry.prev = null;<br>        entry.next = head;<br>        <br>        if (head != null) {<br>            head.prev = entry;<br>        }<br>        <br>        head = entry;<br>        <br>        // Update tail if list was empty<br>        if (tail == null) {<br>            tail = entry;<br>        }<br>    }<br>    <br>    /**<br>     * Add new entry to front of linked list<br>     */<br>    private void addToFront(CacheEntry&lt;K, V&gt; entry) {<br>        if (head != null) {<br>            head.prev = entry;<br>        }<br>        <br>        entry.next = head;<br>        head = entry;<br>        <br>        if (tail == null) {<br>            tail = entry;<br>        }<br>    }<br>    <br>    /**<br>     * Remove least recently used entry (tail)<br>     */<br>    private void evictTail() {<br>        if (tail != null) {<br>            cache.remove(tail.key);<br>            currentMemoryUsed -= tail.sizeInBytes;<br>            tail = tail.prev;<br>            <br>            if (tail != null) {<br>                tail.next = null;<br>            } else {<br>                head = null;<br>            }<br>        }<br>    }<br>    <br>    /**<br>     * Remove a node from linked list<br>     * Updates currentMemoryUsed and head/tail pointers<br>     */<br>    private void removeNodeFromLinkedList(CacheEntry&lt;K, V&gt; node) {<br>        currentMemoryUsed -= node.sizeInBytes;<br>        <br>        if (node.prev != null) {<br>            node.prev.next = node.next;<br>        }<br>        <br>        if (node.next != null) {<br>            node.next.prev = node.prev;<br>        }<br>        <br>        if (node == head) {<br>            head = node.next;<br>        }<br>        <br>        if (node == tail) {<br>            tail = node.prev;<br>        }<br>    }<br>    <br>    /**<br>     * Remove all expired entries from cache<br>     * Called when cache reaches 95% capacity<br>     */<br>    private void cleanupExpiredEntries() {<br>        CacheEntry&lt;K, V&gt; current = tail;<br>        <br>        while (current != null) {<br>            if (current.isExpired()) {<br>                cache.remove(current.key);<br>                CacheEntry&lt;K, V&gt; prev = current.prev;<br>                removeNodeFromLinkedList(current);<br>                current = prev;<br>            } else {<br>                current = current.prev;<br>            }<br>        }<br>    }<br>    <br>    /**<br>     * Save all non-expired entries to disk<br>     * Called on shutdown<br>     * Format: JSON-like structure with key, value, ttl, size<br>     */<br>    public void saveToDisk() {<br>        if (persistenceFilePath == null) {<br>            return;<br>        }<br>        <br>        lock.readLock().lock();<br>        try {<br>            StringBuilder sb = new StringBuilder();<br>            CacheEntry&lt;K, V&gt; current = head;<br>            <br>            // Iterate through linked list (most recent to least recent)<br>            while (current != null) {<br>                // Only save non-expired entries<br>                if (!current.isExpired()) {<br>                    long remainingTTL = current.expirationTime - System.currentTimeMillis();<br>                    sb.append(current.key).append(&quot;|&quot;)<br>                      .append(current.value).append(&quot;|&quot;)<br>                      .append(remainingTTL).append(&quot;|&quot;)<br>                      .append(current.sizeInBytes).append(&quot;\n&quot;);<br>                }<br>                current = current.next;<br>            }<br>            <br>            // Write to file<br>            try (FileWriter fw = new FileWriter(persistenceFilePath)) {<br>                fw.write(sb.toString());<br>            } catch (IOException e) {<br>                System.err.println(&quot;Error saving cache to disk: &quot; + e.getMessage());<br>            }<br>        } finally {<br>            lock.readLock().unlock();<br>        }<br>    }<br>    <br>    /**<br>     * Load cache from disk on startup<br>     * Reads entries saved in format: key|value|ttl|size<br>     */<br>    private void loadFromDisk() {<br>        File file = new File(persistenceFilePath);<br>        if (!file.exists()) {<br>            return;<br>        }<br>        <br>        try (BufferedReader br = new BufferedReader(new FileReader(file))) {<br>            String line;<br>            while ((line = br.readLine()) != null) {<br>                if (line.trim().isEmpty()) continue;<br>                <br>                String[] parts = line.split(&quot;\\|&quot;);<br>                if (parts.length == 4) {<br>                    K key = (K) parts[0];<br>                    V value = (V) parts[1];<br>                    long ttl = Long.parseLong(parts[2]);<br>                    long size = Long.parseLong(parts[3]);<br>                    <br>                    // Only load if TTL is still valid<br>                    if (ttl &gt; 0) {<br>                        put(key, value, ttl, size);<br>                    }<br>                }<br>            }<br>        } catch (IOException e) {<br>            System.err.println(&quot;Error loading cache from disk: &quot; + e.getMessage());<br>        }<br>    }<br>    <br>    /**<br>     * Graceful shutdown: save cache and cleanup<br>     */<br>    public void shutdown() {<br>        lock.writeLock().lock();<br>        try {<br>            saveToDisk();<br>            cache.clear();<br>            head = null;<br>            tail = null;<br>            currentMemoryUsed = 0;<br>        } finally {<br>            lock.writeLock().unlock();<br>        }<br>    }<br>    <br>    // Getters for testing<br>    public long getCurrentMemoryUsed() {<br>        lock.readLock().lock();<br>        try {<br>            return currentMemoryUsed;<br>        } finally {<br>            lock.readLock().unlock();<br>        }<br>    }<br>    <br>    public long getMaxMemoryBytes() {<br>        return maxMemoryBytes;<br>    }<br>    <br>    public int getCacheSize() {<br>        lock.readLock().lock();<br>        try {<br>            return cache.size();<br>        } finally {<br>            lock.readLock().unlock();<br>        }<br>    }<br>}<br><br>/**<br> * Node in the doubly-linked list<br> * Stores: key, value, metadata (TTL, frequency, size)<br> * Plus pointers for linked list navigation<br> */<br>class CacheEntry&lt;K, V&gt; {<br>    K key;<br>    V value;<br>    long lastAccessTime;<br>    int accessFrequency;<br>    long expirationTime;<br>    long sizeInBytes;<br>    <br>    // Doubly linked list pointers<br>    CacheEntry&lt;K, V&gt; prev;<br>    CacheEntry&lt;K, V&gt; next;<br>    <br>    public CacheEntry(K key, V value, long ttlMillis, long sizeInBytes) {<br>        this.key = key;<br>        this.value = value;<br>        this.lastAccessTime = System.currentTimeMillis();<br>        this.accessFrequency = 1;<br>        this.expirationTime = System.currentTimeMillis() + ttlMillis;<br>        this.sizeInBytes = sizeInBytes;<br>        this.prev = null;<br>        this.next = null;<br>    }<br>    <br>    /**<br>     * Update when entry is accessed<br>     */<br>    public void updateAccess() {<br>        this.lastAccessTime = System.currentTimeMillis();<br>        this.accessFrequency++;<br>    }<br>    <br>    /**<br>     * Check if entry has expired<br>     */<br>    public boolean isExpired() {<br>        return System.currentTimeMillis() &gt; expirationTime;<br>    }<br>}</pre><pre>Main method to test the code</pre><pre>import java.util.concurrent.*;<br><br>/**<br> * Comprehensive tests for LRUCache demonstrating:<br> * - Basic LRU eviction<br> * - TTL expiration<br> * - Memory management<br> * - Persistence (save/load)<br> * - Thread-safety (concurrent access)<br> */<br>public class LRUCacheTest {<br>    <br>    public static void main(String[] args) throws InterruptedException {<br>        System.out.println(&quot;=== LRU Cache with TTL, Memory Management, Persistence &amp; Concurrency ===\n&quot;);<br>        <br>        // Test 1: Basic LRU with Memory Management<br>        testBasicLRUWithMemory();<br>        <br>        // Test 2: TTL Expiration<br>        testTTLExpiration();<br>        <br>        // Test 3: Persistence<br>        testPersistence();<br>        <br>        // Test 4: Concurrency (Multiple threads)<br>        testConcurrency();<br>    }<br>    <br>    /**<br>     * Test 1: Basic LRU eviction with memory management<br>     */<br>    public static void testBasicLRUWithMemory() {<br>        System.out.println(&quot;--- Test 1: Basic LRU with Memory Management ---&quot;);<br>        <br>        LRUCache&lt;String, String&gt; cache = new LRUCache&lt;&gt;(1000);  // 1000 bytes max<br>        <br>        // Add entries<br>        cache.put(&quot;entry1&quot;, &quot;value1&quot;, 60000, 400);  // 400 bytes, 60 second TTL<br>        System.out.println(&quot;After entry1: Memory used = &quot; + cache.getCurrentMemoryUsed() + &quot; bytes&quot;);<br>        <br>        cache.put(&quot;entry2&quot;, &quot;value2&quot;, 60000, 400);  // 400 bytes<br>        System.out.println(&quot;After entry2: Memory used = &quot; + cache.getCurrentMemoryUsed() + &quot; bytes&quot;);<br>        <br>        cache.put(&quot;entry3&quot;, &quot;value3&quot;, 60000, 400);  // 400 bytes<br>        System.out.println(&quot;After entry3: Memory used = &quot; + cache.getCurrentMemoryUsed() + &quot; bytes&quot;);<br>        <br>        // This will trigger eviction (entry1 is LRU, will be evicted)<br>        cache.put(&quot;entry4&quot;, &quot;value4&quot;, 60000, 300);  // 300 bytes - triggers while loop<br>        System.out.println(&quot;After entry4: Memory used = &quot; + cache.getCurrentMemoryUsed() + &quot; bytes&quot;);<br>        System.out.println(&quot;Cache size: &quot; + cache.getCacheSize() + &quot; entries&quot;);<br>        <br>        // Verify which entries remain<br>        System.out.println(&quot;entry1: &quot; + cache.get(&quot;entry1&quot;));  // Should be null (evicted)<br>        System.out.println(&quot;entry2: &quot; + cache.get(&quot;entry2&quot;));  // Should exist<br>        System.out.println(&quot;entry3: &quot; + cache.get(&quot;entry3&quot;));  // Should exist<br>        System.out.println(&quot;entry4: &quot; + cache.get(&quot;entry4&quot;));  // Should exist<br>        System.out.println();<br>    }<br>    <br>    /**<br>     * Test 2: TTL expiration<br>     */<br>    public static void testTTLExpiration() throws InterruptedException {<br>        System.out.println(&quot;--- Test 2: TTL Expiration ---&quot;);<br>        <br>        LRUCache&lt;String, String&gt; cache = new LRUCache&lt;&gt;(1000);<br>        <br>        // Add entries with short TTL<br>        cache.put(&quot;token1&quot;, &quot;jwt123&quot;, 2000, 100);  // 2 second TTL<br>        cache.put(&quot;token2&quot;, &quot;jwt456&quot;, 2000, 100);<br>        System.out.println(&quot;After adding tokens: &quot; + cache.getCacheSize() + &quot; entries&quot;);<br>        <br>        System.out.println(&quot;token1: &quot; + cache.get(&quot;token1&quot;));  // Should exist<br>        <br>        System.out.println(&quot;Waiting 3 seconds for TTL to expire...&quot;);<br>        Thread.sleep(3000);<br>        <br>        System.out.println(&quot;token1 after expiration: &quot; + cache.get(&quot;token1&quot;));  // Should be null<br>        System.out.println(&quot;token2 after expiration: &quot; + cache.get(&quot;token2&quot;));  // Should be null<br>        System.out.println(&quot;Cache size after expiration: &quot; + cache.getCacheSize());<br>        System.out.println();<br>    }<br>    <br>    /**<br>     * Test 3: Persistence (save and load)<br>     */<br>    public static void testPersistence() throws InterruptedException {<br>        System.out.println(&quot;--- Test 3: Persistence (Save/Load) ---&quot;);<br>        <br>        String persistenceFile = &quot;./cache_backup.dat&quot;;<br>        <br>        // Create cache and add entries<br>        LRUCache&lt;String, String&gt; cache1 = new LRUCache&lt;&gt;(1000, persistenceFile);<br>        cache1.put(&quot;user1&quot;, &quot;Alice&quot;, 60000, 100);<br>        cache1.put(&quot;user2&quot;, &quot;Bob&quot;, 60000, 100);<br>        cache1.put(&quot;user3&quot;, &quot;Charlie&quot;, 60000, 100);<br>        System.out.println(&quot;Cache 1: Added 3 entries&quot;);<br>        System.out.println(&quot;Cache 1 size before save: &quot; + cache1.getCacheSize());<br>        <br>        // Save to disk<br>        cache1.saveToDisk();<br>        System.out.println(&quot;Cache saved to disk&quot;);<br>        <br>        // Create new cache and load from disk<br>        LRUCache&lt;String, String&gt; cache2 = new LRUCache&lt;&gt;(1000, persistenceFile);<br>        System.out.println(&quot;Cache 2: Loaded from disk&quot;);<br>        System.out.println(&quot;Cache 2 size after load: &quot; + cache2.getCacheSize());<br>        <br>        // Verify data persisted<br>        System.out.println(&quot;user1: &quot; + cache2.get(&quot;user1&quot;));  // Should be Alice<br>        System.out.println(&quot;user2: &quot; + cache2.get(&quot;user2&quot;));  // Should be Bob<br>        System.out.println(&quot;user3: &quot; + cache2.get(&quot;user3&quot;));  // Should be Charlie<br>        <br>        cache1.shutdown();<br>        cache2.shutdown();<br>        System.out.println();<br>    }<br>    <br>    /**<br>     * Test 4: Concurrency (multiple threads accessing cache simultaneously)<br>     */<br>    public static void testConcurrency() throws InterruptedException {<br>        System.out.println(&quot;--- Test 4: Concurrency (Thread-Safe) ---&quot;);<br>        <br>        LRUCache&lt;String, String&gt; cache = new LRUCache&lt;&gt;(10000);  // 10KB cache<br>        <br>        // Create thread pool for concurrent operations<br>        ExecutorService executor = Executors.newFixedThreadPool(5);<br>        <br>        // Simulate 5 threads doing concurrent reads/writes<br>        for (int threadId = 0; threadId &lt; 5; threadId++) {<br>            final int tid = threadId;<br>            <br>            executor.submit(() -&gt; {<br>                try {<br>                    // Each thread adds and retrieves entries<br>                    for (int i = 0; i &lt; 10; i++) {<br>                        String key = &quot;key_&quot; + tid + &quot;_&quot; + i;<br>                        String value = &quot;value_&quot; + tid + &quot;_&quot; + i;<br>                        <br>                        // Write operation (uses write lock)<br>                        cache.put(key, value, 60000, 100);<br>                        <br>                        // Read operation (uses read lock)<br>                        String retrieved = cache.get(key);<br>                        <br>                        if (i % 3 == 0) {<br>                            System.out.println(&quot;Thread &quot; + tid + &quot;: Put and retrieved &quot; + key);<br>                        }<br>                        <br>                        Thread.sleep(10);  // Simulate some work<br>                    }<br>                } catch (InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                }<br>            });<br>        }<br>        <br>        // Wait for all threads to complete<br>        executor.shutdown();<br>        executor.awaitTermination(30, TimeUnit.SECONDS);<br>        <br>        System.out.println(&quot;All threads completed&quot;);<br>        System.out.println(&quot;Final cache size: &quot; + cache.getCacheSize() + &quot; entries&quot;);<br>        System.out.println(&quot;Final memory used: &quot; + cache.getCurrentMemoryUsed() + &quot; bytes&quot;);<br>        System.out.println();<br>    }<br>}</pre><h3>Algorithm Complexity</h3><p>Operation Time Why get(key) O(1) HashMap lookup + move to front (4 pointer updates) put(key, value) O(1) HashMap insert + linked list add (amortized) evict O(1) Remove tail node (4 pointer updates) cleanup expired O(n) Must iterate all entries, but only when 95% full</p><p><strong>Space Complexity:</strong> O(n) where n is number of entries</p><h3>Usage Examples</h3><h3>Example 1: Caching JWT Tokens</h3><pre>LRUCache&lt;String, String&gt; tokenCache = new LRUCache&lt;&gt;(<br>    1_000_000,           // 1MB max<br>    &quot;./tokens.dat&quot;       // Persist to file<br>);</pre><pre>// User logs in<br>String token = generateJWT();<br>tokenCache.put(userId, token, 15 * 60 * 1000, token.length());<br>// 15 minute TTL, size = token length</pre><pre>// User makes request<br>String cachedToken = tokenCache.get(userId);<br>if (cachedToken != null) {<br>    // Token valid and in cache<br>} else {<br>    // Token expired or not in cache, re-authenticate<br>}</pre><h3>Example 2: Caching Database Queries</h3><pre>LRUCache&lt;String, UserProfile&gt; profileCache = new LRUCache&lt;&gt;(<br>    50_000_000  // 50MB max<br>);</pre><pre>String cacheKey = &quot;user:&quot; + userId;<br>UserProfile profile = profileCache.get(cacheKey);</pre><pre>if (profile == null) {<br>    profile = database.getUserProfile(userId);<br>    profileCache.put(<br>        cacheKey, <br>        profile, <br>        60 * 60 * 1000,  // 1 hour TTL<br>        estimatedSize    // Size in bytes<br>    );<br>}</pre><h3>Example 3: Multi-threaded Web Server</h3><pre>LRUCache&lt;String, String&gt; cache = new LRUCache&lt;&gt;(100_000_000);</pre><pre>// Multiple HTTP handler threads<br>ExecutorService handlers = Executors.newFixedThreadPool(10);<br>handlers.submit(() -&gt; {<br>    String data = cache.get(request.getKey());  // Concurrent reads<br>    // Thread-safe! ReadWriteLock handles synchronization<br>});</pre><h3>Key Design Decisions</h3><h3>1. Why ReadWriteLock over Synchronized?</h3><ul><li>Multiple threads can read simultaneously</li><li>Only write operations block other threads</li><li>Better throughput for read-heavy workloads (typical for caches)</li></ul><h3>2. Why cleanup at 95% not 100%?</h3><ul><li>Safety margin before hitting exact limit</li><li>Reduces frequency of cleanup operations</li><li>Gives time for expired entries to accumulate</li></ul><h3>3. Why save only non-expired entries?</h3><ul><li>Expired entries are worthless after restart</li><li>Saves disk space</li><li>Faster load time on startup</li></ul><h3>4. Why lazy + eager deletion for expiration?</h3><ul><li>Lazy: Responds immediately when entry accessed</li><li>Eager: Prevents waste when cache is nearly full</li><li>Together: Efficient memory usage</li></ul><h3>5. Why memory-based, not count-based?</h3><ul><li>Real world: entries have different sizes</li><li>Fairer allocation (100MB cache, not “100 entries”)</li><li>More realistic for production systems</li></ul><h3>What’s Not Included (and Why)</h3><h3>1. LFU (Least Frequently Used) Eviction</h3><ul><li>Added complexity for questionable benefit</li><li>LRU sufficient for most use cases</li><li>Can be added as alternative eviction policy</li></ul><h3>2. Distributed Caching</h3><ul><li>This is single-machine in-memory cache</li><li>Redis/Memcached handle distribution</li><li>Can be built on top of this</li></ul><h3>3. Automatic Persistence</h3><ul><li>Only on shutdown (user control)</li><li>Avoids constant disk writes (would destroy latency)</li><li>Acceptable risk for caches (not durable storage)</li></ul><h3>4. Statistics/Metrics</h3><ul><li>Hit rate, miss rate, eviction stats</li><li>Could be added with counters</li><li>Left out for simplicity</li></ul><h3>Testing Checklist</h3><ul><li>[x] Basic LRU eviction when full</li><li>[x] Memory-based capacity limits</li><li>[x] TTL expiration (lazy + eager)</li><li>[x] Persistence (save/load)</li><li>[x] Concurrent access (multiple threads)</li><li>[x] Edge cases (single entry, all expired, etc)</li></ul><h3>Real-World Applications</h3><ol><li><strong>Web Application Caching</strong> — Cache session data, user profiles</li><li><strong>API Response Caching</strong> — Cache frequently accessed endpoints</li><li><strong>Database Query Cache</strong> — Cache expensive queries</li><li><strong>Token Storage</strong> — JWT/OAuth token caching</li><li><strong>Rate Limiting</strong> — Track request counts with TTL</li><li><strong>Content Delivery</strong> — Cache frequently accessed content</li></ol><h3>Performance Characteristics</h3><p><strong>Typical Operations:</strong></p><ul><li>get(): &lt; 1 microsecond</li><li>put(): &lt; 1 microsecond</li><li>eviction(): &lt; 1 microsecond</li></ul><p><strong>Bottleneck:</strong> Disk I/O during persistence (milliseconds)</p><p><strong>Memory Overhead:</strong></p><ul><li>Per entry: ~64 bytes (Java object overhead + pointers)</li><li>Plus size of key and value</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5e6bfbce5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Key-Value Store Database]]></title>
            <link>https://medium.com/@dolapavan/key-value-store-database-fecc250b2efc?source=rss-25b3cd8d553e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fecc250b2efc</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Dolapavan]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 21:00:56 GMT</pubDate>
            <atom:updated>2026-01-14T21:00:56.315Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lets look at Bigger picture on what we are building</h3><p>component1: Storage Engine — Append-only Log</p><p>component2: Indexing — Persistent Indexer using Checkpoints</p><p>component3- Write Ahead Log</p><p>component4- Compaction — deleting garbage data</p><p>component 5- Concurrency control</p><h3>let start with Storage Engine</h3><p>In our storage engine we have three main functions put,get,delete</p><p>-we will store the data in a text file in the format</p><p>PUT,name,Alice</p><p>PUT,age,25</p><p>PUT,name,Bob</p><p>DELETE,age</p><p>PUT,city,NYC</p><p>-we will skip if we found delete word</p><p>-with the get function we will get the latest values</p><h3>Component 2 Indexing</h3><p>-For this we are building Persistent Indexing</p><p>-why do we need indexing it will help to fetch data faster -After every five operations we will create a checkpoint so when we cold start the database the startup time will be fast</p><h3>Component 3 — write Ahead Log</h3><p>-In simple terms we will write to the log before updating memory</p><h3>Component 4 — Compaction</h3><p>-As we only want the latest updated values the old values become garbage -So we will run a program after 30 operations to delete the old file and create a new file with latest values</p><p>-By we can save lot of time during startup and size of the file</p><h3>Component 5 — Concurrency Control</h3><p>-let us look at a scenario where a user is read a value an another user is updating the value at same time which will lead to data mismatch. -So will put a lock when we are updating data so other programs have to wait until it is completed</p><p>-we will use write locks for put and delete and read locks for get</p><h3>Actual implementation</h3><pre>import java.io.*;<br>import java.util.HashMap;<br>import java.util.Map;<br>import java.util.concurrent.locks.Lock;<br>import java.util.concurrent.locks.ReadWriteLock;<br>import java.util.concurrent.locks.ReentrantReadWriteLock;<br><br>public class SimpleStorage {<br>// required fields<br>    private String filename;<br>    private PrintWriter writer;<br>    private int currentLineNumber = 0;        <br>    private int checkpointLineNumber = 0;     <br>    private int operationsSinceCheckpoint = 0; <br>    private static final int CHECKPOINT_THRESHOLD = 5;<br>    private HashMap&lt;String, String&gt; index; <br>    private static final int COMPACTION_THRESHOLD = 30;<br>    private int totalOperations = 0; <br>    private ReadWriteLock lock;<br>    private Lock readLock;<br>    private Lock writeLock;<br>//constructor<br>    public SimpleStorage(String filename) throws IOException {<br>        this.filename = filename;<br>        this.writer = new PrintWriter(new FileWriter(filename, true));<br>        this.index = new HashMap&lt;&gt;();<br>        this.lock = new ReentrantReadWriteLock();<br>        this.readLock = lock.readLock();<br>        this.writeLock = lock.writeLock();<br>        loadCheckpoint();<br>        replayLog();<br>    }<br>// our put method with cconcurrency implementation<br>    public void put(String key, String value) {<br>        writeLock.lock();<br>        try {<br>            writer.println(&quot;PUT,&quot; + key + &quot;,&quot; + value);<br>            writer.flush();<br>            index.put(key, value);<br>            operationsSinceCheckpoint++;<br>            totalOperations++;<br>            if (operationsSinceCheckpoint == CHECKPOINT_THRESHOLD) {<br>                checkpoint();<br>                operationsSinceCheckpoint = 0;<br>            }<br>        } finally {<br>            writeLock.unlock();<br>        }<br>    }<br>    public void delete(String key) {<br>        writeLock.lock();<br>        try {<br>            writer.println(&quot;DELETE,&quot; + key);<br>            writer.flush();<br>            index.remove(key);<br>            operationsSinceCheckpoint++;<br>            totalOperations++;<br>            if (operationsSinceCheckpoint == CHECKPOINT_THRESHOLD) {<br>                checkpoint();<br>                operationsSinceCheckpoint = 0;<br>            }<br>        } finally {<br>            writeLock.unlock();<br>        }<br>    }<br>// our checkpoint method after 5 operations<br>    private void checkpoint() {<br>        try {<br>            if (totalOperations % COMPACTION_THRESHOLD == 0) {<br>// calling our compact method if it is more than 30 opertaions<br>                compact();<br>                totalOperations = 0; <br>            } else {<br>                countLines(); <br>            }<br>            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(&quot;checkpoint.dat&quot;));<br>            out.writeInt(currentLineNumber);<br>            out.writeObject(index);<br>            out.close();<br>            checkpointLineNumber = currentLineNumber;<br>            System.out.println(&quot;Checkpoint created at line &quot; + currentLineNumber);<br>        } catch (IOException e) {<br>            System.err.println(&quot;Checkpoint failed: &quot; + e.getMessage());<br>        }<br>    }<br>    private void countLines() throws IOException {<br>        BufferedReader reader = new BufferedReader(new FileReader(filename));<br>        int count = 0;<br>        while (reader.readLine() != null) {<br>            count++;<br>        }<br>        reader.close();<br>        currentLineNumber = count;<br>    }<br>    public void close() throws IOException {<br>        writeLock.lock();  <br>        try {<br>            checkpoint(); <br>            writer.close();<br>        } finally {<br>            writeLock.unlock();<br>        }<br>    }<br>    public String get(String key) throws IOException {<br>        readLock.lock();<br>        try {<br>            return index.get(key);<br>        } finally {<br>            readLock.unlock();<br>        }<br>    }<br>// load checkpoint loads our file into memory on startup<br>    private void loadCheckpoint() {<br>        try {<br>            ObjectInputStream in = new ObjectInputStream(new FileInputStream(&quot;checkpoint.dat&quot;));<br>      <br>            checkpointLineNumber = in.readInt();<br>            index = (HashMap&lt;String, String&gt;) in.readObject();<br>            in.close();<br>            System.out.println(&quot;Loaded checkpoint from line &quot; + checkpointLineNumber);<br>        } catch (FileNotFoundException e) {<br>            System.out.println(&quot;No checkpoint found, starting fresh&quot;);<br>        } catch (IOException | ClassNotFoundException e) {<br>            System.err.println(&quot;Failed to load checkpoint: &quot; + e.getMessage());<br>        }<br>    }<br>// fill our in memory indexer hashmap on start<br>    private void replayLog() throws IOException {<br>        BufferedReader reader = new BufferedReader(new FileReader(filename));<br>        String line;<br>        int lineNumber = 0;<br>        while ((line = reader.readLine()) != null) {<br>            lineNumber++;<br>            if (lineNumber &lt;= checkpointLineNumber) {<br>                continue;<br>            }<br>            String[] values = line.split(&quot;,&quot;);<br>            if (values[0].equals(&quot;DELETE&quot;)) {<br>                index.remove(values[1]);<br>            } else<br>                index.put(values[1], values[2]);<br>        }<br>        currentLineNumber = lineNumber;<br>        System.out.println(&quot;currentline after replay: &quot; + currentLineNumber);<br>        reader.close();<br>    }<br>    private void compact() throws IOException {<br>        System.out.println(&quot;Starting compaction...&quot;);<br>        writer.close();<br>        File tempFile = new File(filename + &quot;.tmp&quot;);<br>        PrintWriter tempWriter = new PrintWriter(new FileWriter(tempFile));<br>        currentLineNumber = 0;<br>   <br>        for (Map.Entry&lt;String, String&gt; entry : index.entrySet()) {<br>            String key = entry.getKey();<br>            String value = entry.getValue();<br>            tempWriter.println(&quot;PUT,&quot; + key + &quot;,&quot; + value);<br>            currentLineNumber++;<br>        }<br>        tempWriter.flush();<br>        tempWriter.close();<br>        File oldFile = new File(filename);<br>        oldFile.delete();<br>        File newfile = new File(filename);<br>        tempFile.renameTo(newfile);<br>        writer = new PrintWriter(new FileWriter(filename, true));<br>        checkpointLineNumber = currentLineNumber; <br>        System.out.println(&quot;Compaction complete. Lines: &quot; + currentLineNumber);<br>    }</pre><h3>What we Built So Far Component 1: Storage Engine</h3><ul><li>Append-only log (never lose data)</li><li>Durable writes with flush</li><li>Handles updates and deletes via tombstones</li></ul><h3>Component 2: Indexing</h3><ul><li>In-memory HashMap for O(1) lookups</li><li>Persistent checkpoints for fast startup</li><li>Smart replay from checkpoint</li></ul><h3>Component 3: Write-Ahead Log (WAL)</h3><ul><li>Always write to log before updating memory</li><li>Crash recovery by replaying log</li><li>Durability guarantees</li></ul><h3>Component 4: Compaction</h3><ul><li>Removes garbage (old versions, deleted keys)</li><li>Reclaims disk space</li><li>Triggered automatically every N operations</li></ul><h3>Component 5: Concurrency Control</h3><ul><li>ReadWriteLock for thread safety</li><li>Multiple readers can work simultaneously</li><li>Writers get exclusive access</li><li>No data corruption, no race conditions</li></ul><h3>What You’ve Learned</h3><p><strong>Why databases are slow or fast</strong></p><ul><li>Disk I/O is the bottleneck</li><li>Indexing makes reads fast</li><li>Compaction trades CPU for disk space</li><li>Locks serialize access (safety vs speed)</li></ul><p><strong>How real databases work</strong></p><ul><li>PostgreSQL, MySQL, MongoDB all use these concepts</li><li>LSM-Trees (LevelDB, RocksDB) work exactly like this</li><li>Redis uses similar in-memory indexes</li></ul><p><strong>Computer Science fundamentals</strong></p><ul><li>File I/O and buffering</li><li>Data structures (HashMap)</li><li>Concurrency (locks, race conditions)</li><li>Trade-offs (performance vs durability)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fecc250b2efc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>