<?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 Suneel Kandali on Medium]]></title>
        <description><![CDATA[Stories by Suneel Kandali on Medium]]></description>
        <link>https://medium.com/@suneelr.kandali?source=rss-32a9b3ac847------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kC1xXaH1fAQrF7L4J9ugmw.jpeg</url>
            <title>Stories by Suneel Kandali on Medium</title>
            <link>https://medium.com/@suneelr.kandali?source=rss-32a9b3ac847------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:08:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suneelr.kandali/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[Spring Boot REST API — Field Selection & Filters Demo]]></title>
            <link>https://medium.com/@suneelr.kandali/spring-boot-rest-api-field-selection-filters-demo-2dcd9ce514ad?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dcd9ce514ad</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[field-selection]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[filters]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 15:38:03 GMT</pubDate>
            <atom:updated>2026-07-26T15:38:03.247Z</atom:updated>
            <content:encoded><![CDATA[<p>A Spring Boot RESTful web service for employee management with <strong>dynamic field selection</strong> and <strong>filtering</strong> capabilities using JPA Criteria API. This project demonstrates how to build a flexible API that allows clients to request only the fields they need and apply dynamic filter conditions.</p><h3>Features</h3><ul><li><strong>CRUD Operations</strong> — Create, Read, Update, Delete employees</li><li><strong>Dynamic Field Selection</strong> — Request only specific employee attributes in the response (e.g., only id, firstName, department)</li><li><strong>Dynamic Filtering</strong> — Apply filters with operators like EQUALS, NOT_EQUALS, GREATER_THAN, LESS_THAN, LIKE, IN</li><li><strong>JPA Criteria API</strong> — Uses programmatic, type-safe queries for dynamic projections and predicates</li><li><strong>PostgreSQL</strong> — Persistent data storage</li><li><strong>Docker Compose</strong> — Easy containerized setup with Spring Boot and PostgreSQL</li><li><strong>Lombok</strong> — Reduces boilerplate code</li></ul><h3>Tech Stack</h3><p>TechnologyVersionJava17Spring Boot3.2.5Spring Data JPA(via Spring Boot)PostgreSQL15 (Alpine)Maven3.9.6Lombok(latest)Docker(Compose V2)</p><h3>Project Structure</h3><pre>springboot-restapi-fieldselection-filters-demo/<br>├── Dockerfile                          # Multi-stage Docker build<br>├── docker-compose.yml                  # PostgreSQL + Spring Boot setup<br>├── pom.xml                             # Maven project configuration<br>├── .gitignore<br>├── README.md<br>└── src/<br>    └── main/<br>        ├── java/<br>        │   └── com/example/employee/<br>        │       ├── EmployeeServiceApplication.java   # Main entry point<br>        │       ├── controller/<br>        │       │   └── EmployeeController.java       # REST endpoints<br>        │       ├── dto/<br>        │       │   ├── FieldSelectionRequest.java    # Request DTO for search<br>        │       │   └── FilterCriterion.java          # Filter condition DTO<br>        │       ├── entity/<br>        │       │   └── Employee.java                 # JPA entity<br>        │       ├── repository/<br>        │       │   └── EmployeeRepository.java       # JPA repository<br>        │       └── service/<br>        │           └── EmployeeService.java          # Business logic &amp; Criteria API<br>        └── resources/<br>            └── application.yml                     # Configuration</pre><h3>Entity — Employee</h3><p>FieldTypeDescriptionidLongPrimary key (auto-gen)firstNameStringEmployee first namelastNameStringEmployee last nameemailStringEmail addressdepartmentStringDepartment namesalaryBigDecimalSalary amountjoiningDateLocalDateDate of joining</p><h3>Prerequisites</h3><ul><li><strong>Docker</strong> &amp; <strong>Docker Compose</strong></li><li><strong>curl</strong> or any API client (Postman, Insomnia)</li></ul><h3>Getting Started</h3><h3>1. Clone the Repository</h3><pre>git clone https://github.com/suneelkandali/springboot-restapi-fieldselection-filters-demo.git<br>cd springboot-restapi-fieldselection-filters-demo</pre><p>If the repository is already cloned, ensure you’re on the latest code:</p><pre>git pull origin main</pre><h3>2. Run with Docker Compose</h3><p>Build and start both the PostgreSQL database and the Spring Boot application:</p><pre>docker compose up --build</pre><ul><li>The application will be available at <a href="http://localhost:8080/"><strong>http://localhost:8080</strong></a></li><li>PostgreSQL runs on port <strong>5432</strong></li><li>Tables are auto-created by Hibernate (ddl-auto: update)</li></ul><p>To run in detached mode:</p><pre>docker compose up --build -d</pre><h3>API Endpoints</h3><h3>1. Create Employee</h3><pre>curl -X POST http://localhost:8080/api/employees \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;firstName&quot;: &quot;John&quot;,<br>    &quot;lastName&quot;: &quot;Doe&quot;,<br>    &quot;email&quot;: &quot;john.doe@example.com&quot;,<br>    &quot;department&quot;: &quot;Engineering&quot;,<br>    &quot;salary&quot;: 85000,<br>    &quot;joiningDate&quot;: &quot;2024-01-15&quot;<br>  }&#39;</pre><p><strong>Response:</strong> 201 Created</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;firstName&quot;: &quot;John&quot;,<br>  &quot;lastName&quot;: &quot;Doe&quot;,<br>  &quot;email&quot;: &quot;john.doe@example.com&quot;,<br>  &quot;department&quot;: &quot;Engineering&quot;,<br>  &quot;salary&quot;: 85000,<br>  &quot;joiningDate&quot;: &quot;2024-01-15&quot;<br>}</pre><h3>2. Get Employee by ID</h3><pre>curl http://localhost:8080/api/employees/1</pre><h3>3. Update Employee</h3><pre>curl -X PUT http://localhost:8080/api/employees/1 \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;firstName&quot;: &quot;John&quot;,<br>    &quot;lastName&quot;: &quot;Smith&quot;,<br>    &quot;email&quot;: &quot;john.smith@example.com&quot;,<br>    &quot;department&quot;: &quot;Engineering&quot;,<br>    &quot;salary&quot;: 90000,<br>    &quot;joiningDate&quot;: &quot;2024-01-15&quot;<br>  }&#39;</pre><h3>4. Delete Employee</h3><pre>curl -X DELETE http://localhost:8080/api/employees/1</pre><h3>5. Search with Dynamic Field Selection &amp; Filters (Core Feature)</h3><pre>curl -X POST http://localhost:8080/api/employees/search \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;fields&quot;: [&quot;id&quot;, &quot;firstName&quot;, &quot;department&quot;, &quot;salary&quot;],<br>    &quot;filters&quot;: [<br>      { &quot;field&quot;: &quot;department&quot;, &quot;operator&quot;: &quot;EQUALS&quot;, &quot;value&quot;: &quot;Engineering&quot; },<br>      { &quot;field&quot;: &quot;salary&quot;, &quot;operator&quot;: &quot;GREATER_THAN&quot;, &quot;value&quot;: &quot;50000&quot; }<br>    ]<br>  }&#39;</pre><p><strong>Response:</strong> 200 OK</p><pre>[<br>  {<br>    &quot;id&quot;: 1,<br>    &quot;firstName&quot;: &quot;John&quot;,<br>    &quot;department&quot;: &quot;Engineering&quot;,<br>    &quot;salary&quot;: 85000<br>  }<br>]</pre><h3>Testing Instructions</h3><h3>Seed Sample Data</h3><p>Run these curl commands to populate the database with sample employees:</p><pre># Employee 1<br>curl -X POST http://localhost:8080/api/employees \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;firstName&quot;:&quot;Alice&quot;,&quot;lastName&quot;:&quot;Johnson&quot;,&quot;email&quot;:&quot;alice@example.com&quot;,&quot;department&quot;:&quot;Engineering&quot;,&quot;salary&quot;:95000,&quot;joiningDate&quot;:&quot;2023-03-10&quot;}&#39;</pre><pre># Employee 2<br>curl -X POST <a href="http://localhost:8080/api/employees">http://localhost:8080/api/employees</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;firstName&quot;:&quot;Bob&quot;,&quot;lastName&quot;:&quot;Smith&quot;,&quot;email&quot;:&quot;bob@example.com&quot;,&quot;department&quot;:&quot;Marketing&quot;,&quot;salary&quot;:72000,&quot;joiningDate&quot;:&quot;2022-07-22&quot;}&#39;</pre><pre># Employee 3<br>curl -X POST <a href="http://localhost:8080/api/employees">http://localhost:8080/api/employees</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;firstName&quot;:&quot;Charlie&quot;,&quot;lastName&quot;:&quot;Brown&quot;,&quot;email&quot;:&quot;charlie@example.com&quot;,&quot;department&quot;:&quot;Engineering&quot;,&quot;salary&quot;:110000,&quot;joiningDate&quot;:&quot;2021-11-05&quot;}&#39;</pre><pre># Employee 4<br>curl -X POST <a href="http://localhost:8080/api/employees">http://localhost:8080/api/employees</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;firstName&quot;:&quot;Diana&quot;,&quot;lastName&quot;:&quot;Prince&quot;,&quot;email&quot;:&quot;diana@example.com&quot;,&quot;department&quot;:&quot;HR&quot;,&quot;salary&quot;:65000,&quot;joiningDate&quot;:&quot;2024-05-01&quot;}&#39;</pre><pre># Employee 5<br>curl -X POST <a href="http://localhost:8080/api/employees">http://localhost:8080/api/employees</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;firstName&quot;:&quot;Edward&quot;,&quot;lastName&quot;:&quot;Norton&quot;,&quot;email&quot;:&quot;edward@example.com&quot;,&quot;department&quot;:&quot;Marketing&quot;,&quot;salary&quot;:78000,&quot;joiningDate&quot;:&quot;2023-09-18&quot;}&#39;</pre><h3>Test Field Selection Only</h3><p>Request only id, firstName, and email fields:</p><pre>curl -X POST http://localhost:8080/api/employees/search \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;fields&quot;: [&quot;id&quot;, &quot;firstName&quot;, &quot;email&quot;]<br>  }&#39;</pre><h3>Test Filters Only (Returns all fields)</h3><p>Filter employees in Engineering with salary less than 100000:</p><pre>curl -X POST http://localhost:8080/api/employees/search \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;filters&quot;: [<br>      { &quot;field&quot;: &quot;department&quot;, &quot;operator&quot;: &quot;EQUALS&quot;, &quot;value&quot;: &quot;Engineering&quot; },<br>      { &quot;field&quot;: &quot;salary&quot;, &quot;operator&quot;: &quot;LESS_THAN&quot;, &quot;value&quot;: &quot;100000&quot; }<br>    ]<br>  }&#39;</pre><h3>Test LIKE Operator</h3><p>Search for employees whose first name contains “Al”:</p><pre>curl -X POST http://localhost:8080/api/employees/search \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;fields&quot;: [&quot;id&quot;, &quot;firstName&quot;, &quot;email&quot;, &quot;department&quot;],<br>    &quot;filters&quot;: [<br>      { &quot;field&quot;: &quot;firstName&quot;, &quot;operator&quot;: &quot;LIKE&quot;, &quot;value&quot;: &quot;Al&quot; }<br>    ]<br>  }&#39;</pre><h3>Test IN Operator</h3><p>Filter employees from Engineering or HR departments:</p><pre>curl -X POST http://localhost:8080/api/employees/search \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;fields&quot;: [&quot;id&quot;, &quot;firstName&quot;, &quot;department&quot;, &quot;salary&quot;],<br>    &quot;filters&quot;: [<br>      { &quot;field&quot;: &quot;department&quot;, &quot;operator&quot;: &quot;IN&quot;, &quot;value&quot;: [&quot;Engineering&quot;, &quot;HR&quot;] }<br>    ]<br>  }&#39;</pre><h3>Test NOT_EQUALS Operator</h3><p>Employees not in Marketing:</p><pre>curl -X POST http://localhost:8080/api/employees/search \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;fields&quot;: [&quot;id&quot;, &quot;firstName&quot;, &quot;department&quot;],<br>    &quot;filters&quot;: [<br>      { &quot;field&quot;: &quot;department&quot;, &quot;operator&quot;: &quot;NOT_EQUALS&quot;, &quot;value&quot;: &quot;Marketing&quot; }<br>    ]<br>  }&#39;</pre><h3>Test Empty Fields (Returns All Fields)</h3><pre>curl -X POST http://localhost:8080/api/employees/search \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;filters&quot;: [<br>      { &quot;field&quot;: &quot;salary&quot;, &quot;operator&quot;: &quot;GREATER_THAN&quot;, &quot;value&quot;: &quot;70000&quot; }<br>    ]<br>  }&#39;</pre><h3>Supported Filter Operators</h3><p>OperatorDescriptionExample ValueEQUALSExact match&quot;Engineering&quot;NOT_EQUALSNot equal to&quot;Marketing&quot;LIKEPattern match (case-insensitive)&quot;Al&quot;GREATER_THANGreater than (numbers/dates)&quot;50000&quot;LESS_THANLess than (numbers/dates)&quot;100000&quot;INMember of list[&quot;Eng&quot;, &quot;HR&quot;]</p><h3>Clean Up Resources</h3><h3>Stop Docker Containers</h3><pre># Stop and remove containers, networks<br>docker compose down</pre><pre># Also remove the volume (deletes all persisted data)<br>docker compose down -v</pre><h3>How It Works</h3><p>The core functionality is implemented in EmployeeService.java using the <strong>JPA Criteria API</strong>:</p><ol><li><strong>Dynamic Projection</strong>: The CriteriaQuery&lt;Tuple&gt; is constructed with selected fields from the request. If no fields are specified, all entity attributes are included.</li><li><strong>Dynamic Filtering</strong>: Each FilterCriterion is converted to a JPA Predicate:</li></ol><ul><li>EQUALS / NOT_EQUALS → cb.equal() / cb.notEqual()</li><li>LIKE → cb.like() with case-insensitive pattern matching</li><li>GREATER_THAN / LESS_THAN → Type-aware comparison using buildComparablePredicate() which handles Number, LocalDate, and Comparable types</li><li>IN → path.in() for list membership</li></ul><p><strong>3. Response Mapping</strong>: Tuple results are mapped to List&lt;Map&lt;String, Object&gt;&gt; preserving the key-value structure with aliases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dcd9ce514ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Microservices Orchestration with Saga & Circuit Breaker Patterns — Demo]]></title>
            <link>https://medium.com/@suneelr.kandali/spring-boot-microservices-saga-orchestration-demo-f64d066f2190?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/f64d066f2190</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[saga]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 11:39:55 GMT</pubDate>
            <atom:updated>2026-07-20T02:14:50.459Z</atom:updated>
            <content:encoded><![CDATA[<p>This project demonstrates a simple saga-based workflow and circuit breaker pattern using Spring Boot microservices, PostgreSQL, and Docker Compose.</p><p>It includes:</p><ul><li>an order service</li><li>an inventory service</li><li>an orchestrator service</li><li>a PostgreSQL database</li></ul><h3>Project structure</h3><pre>springboot-microservices-saga-orchestration-demo/<br>├── docker-compose.yml                     # Orchestrates all 4 containers<br>├── init-scripts/<br>│   └── init.sql                           # Seeds inventory table with product 101 (stock: 5)<br>├── postman/<br>│   └── collection.json                    # Postman collection for testing<br>│<br>├── orchestrator-service/                  # Port 8085 — central saga coordinator<br>│   ├── Dockerfile                         # Multi-stage Docker build<br>│   ├── pom.xml                            # Spring Boot 3.2.4, Resilience4j, AOP, Actuator<br>│   └── src/main/java/com/example/saga/orchestrator/<br>│       ├── OrchestratorApplication.java   # @SpringBootApplication entry point<br>│       ├── controller/<br>│       │   └── OrchestratorController.java  # POST /api/saga/checkout<br>│       ├── dto/<br>│       │   ├── OrderRequest.java          # { productId, quantity, price }<br>│       │   ├── OrderResponse.java         # { orderId, status, message }<br>│       │   ├── InventoryRequest.java      # { orderId, productId, quantity }<br>│       │   └── InventoryResponse.java     # { success, message }<br>│       ├── service/<br>│       │   ├── SagaOrchestratorService.java    # Saga workflow + @CircuitBreaker methods<br>│       │   └── CircuitBreakerEventLogger.java  # Logs state transitions &amp; rejected calls<br>│       └── resources/<br>│           └── application.yml            # Resilience4j + Actuator config<br>│<br>├── order-service/                         # Port 8083 — order management<br>│   ├── Dockerfile<br>│   ├── pom.xml<br>│   └── src/main/java/com/example/saga/order/<br>│       ├── OrderApplication.java          # @SpringBootApplication entry point<br>│       ├── controller/<br>│       │   └── OrderController.java       # POST /api/orders, PUT /{id}/confirm, PUT /{id}/cancel<br>│       ├── entity/<br>│       │   └── PurchaseOrder.java         # JPA entity: id, productId, quantity, price, status<br>│       └── repository/<br>│           └── OrderRepository.java       # Spring Data JPA repository<br>│<br>├── inventory-service/                     # Port 8084 — stock management<br>│   ├── Dockerfile<br>│   ├── pom.xml<br>│   ├── resources/<br>│   │   └── application.yml                # DB config for saga_inventory_db<br>│   └── src/main/java/com/example/saga/inventory/<br>│       ├── InventoryApplication.java      # @SpringBootApplication entry point<br>│       ├── controller/<br>│       │   └── InventoryController.java   # POST /api/inventory/reserve<br>│       ├── entity/<br>│       │   └── Inventory.java             # JPA entity: productId, availableStock<br>│       └── repository/<br>│           └── InventoryRepository.java   # Spring Data JPA repository<br>│<br>└── README.md                              # This file</pre><h3>Saga workflow</h3><ul><li>Orchestrator receives an order request.</li><li>Orchestrator calls Order Service to create an order in a PENDING state.</li><li>Orchestrator calls Inventory Service to reserve stock.</li><li>Success: Orchestrator calls Order Service to update the status to COMPLETED.</li><li>Failure (Compensating Transaction): If stock is insufficient, the Inventory Service rejects the request. The Orchestrator catches this and calls the Order Service to CANCEL the order.</li></ul><h3>Circuit Breaker pattern</h3><p>The orchestrator now uses a circuit breaker around the calls to the order and inventory services.</p><p>Why this helps:</p><ul><li>If the downstream service is unavailable or keeps failing, the orchestrator stops repeatedly trying the same failing call.</li><li>After a configured number of failures, the circuit opens and the orchestrator immediately uses a fallback instead of hammering the dependency.</li><li>After a cool-down period, the circuit transitions to half-open state and allows a small number of test calls before fully closing again.</li></ul><p>In this demo the breaker is configured with:</p><ul><li>sliding window of recent calls</li><li>minimum number of calls before evaluating failures</li><li>failure-rate threshold</li><li>open-state wait duration</li><li>half-open recovery probes</li></ul><h3>Prerequisites on a Mac</h3><p>Make sure the following are installed and running:</p><ul><li>Docker Desktop for Mac</li><li>Docker Compose plugin</li><li>Git</li><li>curl (usually already available on macOS)</li></ul><p>Verify Docker is available:</p><pre>docker --version<br>docker compose version</pre><h3>Clone and run locally</h3><p>Clone the repository and start the full stack (Mac):</p><pre>git clone https://github.com/suneelkandali/springboot-microservices-saga-orchestration-demo<br>cd springboot-microservices-saga-orchestration-demo<br>docker compose up --build -d</pre><p>The first run may take a few minutes while Docker builds the images and downloads base images. Wait until postgres-db reports healthy in docker compose ps or check logs.</p><h3>Services and ports</h3><p>Once the containers are running:</p><ul><li>Order service: <a href="http://localhost:8083/">http://localhost:8083</a></li><li>Inventory service: <a href="http://localhost:8084/">http://localhost:8084</a></li><li>Orchestrator service: <a href="http://localhost:8085/">http://localhost:8085</a></li><li>PostgreSQL: localhost:5433</li></ul><h3>Check container status</h3><pre>docker compose ps</pre><p>You should see the PostgreSQL, order, inventory, and orchestrator containers in the Up state.</p><h3>Verify the database seed data</h3><p>The PostgreSQL container initializes a sample inventory row:</p><ul><li>product ID: 101</li><li>stock: 5</li></ul><p>You can verify it with:</p><pre>docker exec -it saga-postgres psql -U postgres -d saga_inventory_db -c &quot;SELECT * FROM inventory;&quot;</pre><h3>Test the application</h3><p>Use the orchestrator endpoint to trigger a checkout flow:</p><pre>curl -X POST http://localhost:8085/api/saga/checkout \<br>  -H &quot;Content-Type: application/json&quot; \<br>   -d &#39;{&quot;productId&quot;:101,&quot;quantity&quot;:2,&quot;price&quot;:99.99}&#39;</pre><p>Expected response:</p><pre>Saga Complete: Order Processed and Finalized successfully.</pre><h3>Demo: Compensation (insufficient inventory)</h3><p>The seed inventory contains product 101 with stock 5. The following sequence demonstrates depletion and a subsequent checkout that triggers the saga compensation (rollback) path.</p><p>Check inventory (before):</p><pre>docker exec -it saga-postgres psql -U postgres -d saga_inventory_db -c &quot;SELECT * FROM inventory;&quot;</pre><p>Successful checkout (reduce stock by 2):</p><pre>curl -X POST http://localhost:8085/api/saga/checkout \<br>   -H &quot;Content-Type: application/json&quot; \<br>   -d &#39;{&quot;productId&quot;:101,&quot;quantity&quot;:2,&quot;price&quot;:99.99}&#39;</pre><p>Successful checkout (reduce stock by 2 again):</p><pre>curl -X POST http://localhost:8085/api/saga/checkout \<br>   -H &quot;Content-Type: application/json&quot; \<br>   -d &#39;{&quot;productId&quot;:101,&quot;quantity&quot;:2,&quot;price&quot;:99.99}&#39;</pre><p>Check inventory (should show 1 left):</p><pre>docker exec -it saga-postgres psql -U postgres -d saga_inventory_db -c &quot;SELECT * FROM inventory;&quot;</pre><p>Checkout that exceeds remaining stock (triggers compensation):</p><pre>curl -X POST http://localhost:8085/api/saga/checkout \<br>   -H &quot;Content-Type: application/json&quot; \<br>   -d &#39;{&quot;productId&quot;:101,&quot;quantity&quot;:2,&quot;price&quot;:99.99}&#39;</pre><p>Expected result: the orchestrator will follow the failure path and perform compensation (order cancellation). The response or logs will indicate a rollback/compensation action.</p><p>You can inspect service logs to see the compensation flow in detail:</p><pre>docker compose logs -f orchestrator-service<br>docker compose logs -f inventory-service</pre><h3>How to test the circuit breaker locally</h3><p>Start the stack:</p><pre>docker compose up --build -d</pre><p>Confirm the orchestrator is healthy:</p><pre>curl -sS http://localhost:8085/actuator/health<br>curl -sS http://localhost:8085/actuator/health/readiness<br>curl -sS http://localhost:8085/actuator/health/liveness<br>curl -sS http://localhost:8085/actuator/metrics<br>curl -sS http://localhost:8085/actuator/metrics/resilience4j.circuitbreaker.calls</pre><p>Simulate repeated downstream failures by stopping the target dependency temporarily (for example, stop the inventory service container):</p><pre>docker compose stop inventory-service</pre><p>Trigger several requests to the orchestrator in a row:</p><pre>for i in 1 2 3 4 5 6 7 8 9 10; do<br>   echo &quot;Request $i&quot;<br>   curl -sS -X POST http://localhost:8085/api/saga/checkout \<br>      -H &quot;Content-Type: application/json&quot; \<br>      -d &#39;{&quot;productId&quot;:101,&quot;quantity&quot;:2,&quot;price&quot;:99.99}&#39;<br>   echo<br>done</pre><p>Watch the orchestrator logs as the breaker opens and falls back:</p><pre>docker compose logs -f orchestrator-service</pre><p>Bring the dependency back up:</p><pre>docker compose start inventory-service</pre><p>After the wait duration has passed, send a few more requests to observe the breaker transition from open to half-open and then close again.</p><p>Expected behavior:</p><ul><li>The first few requests may fail or trigger rollback behavior.</li><li>Once the failure threshold is reached, the breaker opens.</li><li>Further requests should short-circuit quickly through the fallback path instead of continuing to hit the unavailable service.</li></ul><h3>Useful commands</h3><p>Stop everything:</p><pre>docker compose down</pre><p>Stop everything and remove volumes:</p><pre>docker compose down -v</pre><p>View logs for a service:</p><pre>docker compose logs -f orchestrator-service</pre><h3>Health check</h3><p>If the Spring Boot Actuator is enabled you can check service health:</p><pre>curl -sS http://localhost:8085/actuator/health</pre><p>Fallback quick HTTP check (returns HTTP status code):</p><pre>curl -sS -o /dev/null -w &quot;%{http_code}\n&quot; http://localhost:8085/ || echo &quot;no response&quot;</pre><h3>Postman collection</h3><p>You can import a ready Postman collection to exercise the checkout flow: postman/collection.json</p><h3>Troubleshooting</h3><p>If the app does not start correctly:</p><p>Make sure Docker Desktop is running.</p><p>Check container logs:</p><pre>docker compose logs</pre><p>Rebuild and restart:</p><p>docker compose down docker compose up --build -d</p><p>If Docker Desktop prompts for more resources (memory/CPUs), increase them and retry.</p><p>If containers start but services are unreachable from the host, check the mapped host ports in docker compose ps.</p><p>If a port is already in use, change the host port mapping in the Compose file.</p><h3>Troubleshooting the circuit breaker</h3><p>If the circuit breaker does not appear to trigger (e.g. the fallback methods are never called and the metrics always show zero calls), check the following:</p><h3>1. Method visibility</h3><p>The @CircuitBreaker annotation relies on Spring AOP proxies. <strong>Methods annotated with </strong><strong>@CircuitBreaker must be </strong><strong>public</strong>, not private. Spring AOP cannot intercept private method calls, so the circuit breaker aspect will never be invoked.</p><pre>// ❌ Will NOT trigger the circuit breaker<br>@CircuitBreaker(name = &quot;inventoryServiceCircuitBreaker&quot;, fallbackMethod = &quot;fallbackReserveInventory&quot;)<br>private InventoryResponse reserveInventory(InventoryRequest invRequest) { ... }</pre><pre>// ✅ Will trigger the circuit breaker<br>@CircuitBreaker(name = &quot;inventoryServiceCircuitBreaker&quot;, fallbackMethod = &quot;fallbackReserveInventory&quot;)<br>public InventoryResponse reserveInventory(InventoryRequest invRequest) { ... }</pre><h3>2. Self-invocation</h3><p>When a method inside the same class calls another @CircuitBreaker-annotated method, the call bypasses the proxy. Use a self-reference with @Lazy to ensure the proxy is used:</p><pre>@Service<br>public class SagaOrchestratorService {<br>    private final SagaOrchestratorService self;</pre><pre>    @Autowired<br>    public SagaOrchestratorService(@Lazy SagaOrchestratorService self) {<br>        this.self = self;<br>    }</pre><pre>    public String executeSaga(OrderRequest orderRequest) {<br>        // Use self. instead of this. to go through the proxy<br>        OrderResponse orderResponse = self.createOrder(orderRequest);<br>        InventoryResponse invResponse = self.reserveInventory(invRequest);<br>        // ...<br>    }<br>}</pre><h3>3. Missing AOP dependency</h3><p>The resilience4j-spring-boot3 starter requires spring-boot-starter-aop on the classpath for the @CircuitBreaker aspect to work. Without it, the logs will show:</p><pre>Aspects are not activated because AspectJ is not on the classpath.</pre><p>Add the dependency to pom.xml:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-aop&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>4. Verify circuit breaker is working</h3><p>After applying the fixes above, you can confirm the circuit breaker is active by checking:</p><ul><li><strong>Actuator metrics</strong> show non-zero call counts:</li><li>curl -sS <a href="http://localhost:8085/actuator/metrics/resilience4j.circuitbreaker.calls?tag=name:inventoryServiceCircuitBreaker">http://localhost:8085/actuator/metrics/resilience4j.circuitbreaker.calls?tag=name:inventoryServiceCircuitBreaker</a></li><li><strong>Logs</strong> show the CircuitBreakerAspect intercepting calls:</li><li>Created or retrieved circuit breaker &#39;inventoryServiceCircuitBreaker&#39; with failure rate &#39;50.0&#39;</li><li><strong>State transitions</strong> are logged by the CircuitBreakerEventLogger:</li><li>Circuit breaker [inventoryServiceCircuitBreaker] state transition: CLOSED -&gt; OPEN Circuit breaker [inventoryServiceCircuitBreaker] rejected a call because it is open or half-open</li><li><strong>Fallback methods</strong> are invoked instead of throwing exceptions:</li><li>Circuit breaker fallback triggered for inventory service: CircuitBreaker &#39;inventoryServiceCircuitBreaker&#39; is OPEN and does not permit further calls</li></ul><h3>Notes</h3><p>This demo is intended for local development and testing. It uses a simple in-memory-style saga flow with PostgreSQL-backed services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f64d066f2190" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Postgres Redis POC]]></title>
            <link>https://medium.com/@suneelr.kandali/spring-boot-postgres-redis-poc-553dec596446?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/553dec596446</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 02:09:29 GMT</pubDate>
            <atom:updated>2026-07-19T02:14:59.268Z</atom:updated>
            <content:encoded><![CDATA[<p>This repository contains a Spring Boot microservice that stores employee data in PostgreSQL and caches read requests in Redis. After cloning the repo, you can run the full application locally with Docker Compose, using PostgreSQL for persistence and Redis for fast read-through caching.</p><p>The project starts three services locally:</p><ul><li>PostgreSQL as the persistent relational database</li><li>Redis as the distributed cache for employee lookups</li><li>Spring Boot app providing REST APIs for employee CRUD operations</li></ul><p>The application is designed so that GET /api/employees/{id} checks Redis first, then falls back to Postgres when needed, reducing repeated database reads and improving response speed.</p><h3>Project structure</h3><ul><li>Dockerfile - multi-stage build for the Spring Boot app</li><li>docker-compose.yml - starts PostgreSQL, Redis, and the Spring Boot service</li><li>pom.xml - Maven project configuration</li><li>src/main/java/com/example/employee/ - application sources</li><li>EmployeeApplication.java - main Spring Boot app class</li><li>controller/EmployeeController.java - REST API endpoints</li><li>entity/Employee.java - JPA entity</li><li>repository/EmployeeRepository.java - Spring Data repository</li><li>service/EmployeeService.java - business logic and Redis caching</li><li>config/RedisConfig.java - Redis cache configuration</li><li>src/main/resources/application.properties - Spring Boot config</li></ul><h3>Prerequisites</h3><p>These instructions are written for a Mac laptop.</p><ul><li>macOS</li><li>Docker Desktop</li><li>Maven installed (or use a local Maven wrapper if added later)</li><li>DBeaver installed for PostgreSQL access</li><li>RedisInsight installed for Redis access</li></ul><h3>Install DBeaver and RedisInsight with Homebrew</h3><p>If you use Homebrew, install the tools with:</p><pre>brew install --cask dbeaver-community<br>brew install --cask redisinsight</pre><p>Then open them from Spotlight or via:</p><pre>open -a DBeaver<br>open -a &quot;RedisInsight&quot;</pre><h3>Run locally with Docker Compose</h3><p>Clone the repository and change into the project directory:</p><pre>git clone https://github.com/suneelkandali/springboot-postgres-redis<br>cd springboot-postgres-redis-poc</pre><p>If you have a local Redis server running on port 6379, stop it first so Docker can bind the container port safely:</p><pre>brew services stop redis</pre><p>Start the application stack:</p><pre>docker compose down</pre><pre>docker compose up -d --build</pre><p>Confirm the services are running:</p><pre>docker compose ps</pre><h3>Application endpoints</h3><ul><li>Create employee: POST <a href="http://localhost:8080/api/employees">http://localhost:8080/api/employees</a></li><li>Get employee by ID: GET <a href="http://localhost:8080/api/employees/%7Bid%7D">http://localhost:8080/api/employees/{id}</a></li><li>Update employee: PUT <a href="http://localhost:8080/api/employees/%7Bid%7D">http://localhost:8080/api/employees/{id}</a></li><li>Delete employee: DELETE <a href="http://localhost:8080/api/employees/%7Bid%7D">http://localhost:8080/api/employees/{id}</a></li></ul><h3>Example curl commands</h3><p>Create employees:</p><pre>curl -X POST http://localhost:8080/api/employees \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;name&quot;:&quot;Alice&quot;,&quot;email&quot;:&quot;alice@example.com&quot;,&quot;department&quot;:&quot;HR&quot;}&#39;</pre><pre>curl -X POST <a href="http://localhost:8080/api/employees">http://localhost:8080/api/employees</a> \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;name&quot;:&quot;Bob&quot;,&quot;email&quot;:&quot;bob@example.com&quot;,&quot;department&quot;:&quot;Engineering&quot;}&#39;</pre><p>Fetch employees:</p><pre>curl http://localhost:8080/api/employees/1<br>curl http://localhost:8080/api/employees/2</pre><p>Update an employee:</p><pre>curl -X PUT http://localhost:8080/api/employees/1 \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;name&quot;:&quot;Alice Updated&quot;,&quot;email&quot;:&quot;alice.updated@example.com&quot;,&quot;department&quot;:&quot;HR&quot;}&#39;</pre><p>Delete an employee:</p><pre>curl -X DELETE http://localhost:8080/api/employees/1</pre><h3>Verify PostgreSQL with DBeaver</h3><ol><li>Open DBeaver.</li><li>Create a new connection for PostgreSQL.</li><li>Use these connection settings:</li></ol><ul><li>Host: localhost</li><li>Port: 5432</li><li>Database: employee_db</li><li>User: postgres_user</li><li>Password: postgres_password</li></ul><p>Connect and inspect the employee table in the employee_db database.</p><h3>Verify Redis with RedisInsight</h3><ol><li>Open RedisInsight.</li><li>Create a new Redis connection.</li><li>Use these connection settings:</li></ol><ul><li>Host: 127.0.0.1</li><li>Port: 6379</li><li>Database: 0</li></ul><blockquote><em>If RedisInsight does not show cache keys, make sure your local Redis server is stopped and Docker is using port </em><em>6379 for the container.</em></blockquote><p>Refresh the database view and check for keys matching employees::*.</p><h3>Inspect Redis cache directly</h3><p>To inspect Redis cache keys from the container:</p><pre>docker exec employee-redis redis-cli keys &#39;employees*&#39;</pre><p>To inspect a cached employee entry:</p><pre>docker exec employee-redis redis-cli get employees::1</pre><h3>Error handling and downstream connectivity</h3><p>This application includes explicit handling for downstream cache and database availability:</p><ul><li>200 OK when the employee is found by cache or database</li><li>404 Not Found when the employee ID is not present in Redis or Postgres</li><li>503 Service Unavailable when Postgres is unavailable and the employee is not available in the Redis cache</li><li>500 Internal Server Error for other unexpected application failures</li></ul><p>Behavior for GET /api/employees/{id}:</p><ul><li>the service checks Redis cache first</li><li>if the cache contains the employee, the cached record is returned immediately</li><li>if the cache misses, Postgres is queried and the result is written back to Redis</li><li>if Postgres is unavailable, the service falls back to Redis cache and returns the cached employee if present</li><li>if neither Redis nor Postgres can provide the employee, the service returns 404 Not Found</li></ul><p>When Redis is unavailable, cache read/write failures are logged and the service continues to operate against Postgres if it is available.</p><h3>Notes</h3><ul><li>The Redis cache keys are created by Spring Cache using the cache name employees.</li><li>The Docker Compose file currently exposes Redis on host port 6379, so local Redis must be stopped or remapped.</li><li>If you want to avoid a port conflict, change the Redis service port mapping in docker-compose.yml to a different host port, for example 6380:6379.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=553dec596446" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude AI Agent — Tool Use and Loop Demo]]></title>
            <link>https://medium.com/@suneelr.kandali/claude-ai-agent-tool-use-and-loop-demo-96053157cde7?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/96053157cde7</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[claude-certified]]></category>
            <category><![CDATA[agent-loop]]></category>
            <category><![CDATA[claude-tool-use]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 22:55:27 GMT</pubDate>
            <atom:updated>2026-07-02T22:55:27.298Z</atom:updated>
            <content:encoded><![CDATA[<p>A minimal, self-contained demonstration of the <strong>Anthropic tool-use agentic loop</strong> pattern in Python.</p><p>The agent answers customer questions about orders by calling a lookup_order tool (currently backed by mock data). It showcases:</p><ul><li>The <strong>request → tool-call → result → continue</strong> loop</li><li><strong>Structured error categories</strong> (transient, permission, validation, internal) that let Claude decide how to respond</li><li>Proper message history construction required by the Anthropic Messages API</li></ul><h3>Project Structure</h3><pre>claude-certification-agent-tooluse-and-endturn-poc/<br>├── agent.py          # The agentic loop implementation<br>├── api_check.py      # (optional) quick API connectivity test<br>├── requirements.txt  # Python dependencies<br>├── .env              # Your ANTHROPIC_API_KEY (not committed)<br>└── README.md         # This file</pre><h3>Prerequisites</h3><ul><li><strong>Python 3.10+</strong> — macOS ships with Python 2.x by default, so you’ll likely need to install Python 3.</li><li>Install via <a href="https://brew.sh/">Homebrew</a>: brew install python@3.12</li><li>Or download from <a href="https://www.python.org/downloads/">python.org</a></li><li>An <a href="https://console.anthropic.com/">Anthropic API key</a></li></ul><h3>Setup</h3><p><strong>Clone the repository:</strong></p><pre>git clone https://github.com/suneelkandali/claude-certification-agent-tooluse-and-endturn-poc</pre><p><strong>Navigate to the project folder:</strong></p><pre>cd claude-certification-agent-tooluse-and-endturn-poc</pre><p><strong>Create a virtual environment</strong> (recommended):</p><pre>python3 -m venv venv<br>source venv/bin/activate</pre><ul><li><strong>Note:</strong> On macOS, use python3 instead of python to ensure you&#39;re using Python 3. The source venv/bin/activate command activates the virtual environment. You should see (venv) appear in your terminal prompt.</li></ul><p><strong>Install dependencies:</strong></p><pre>pip3 install -r requirements.txt</pre><p><strong>Set your API key:</strong></p><ol><li>Create a .env file in the project root:</li></ol><pre>ANTHROPIC_API_KEY=sk-ant-...</pre><ol><li>The code loads it automatically via python-dotenv.</li></ol><h3>Run</h3><pre>python3 agent.py</pre><p>You should see output similar to:</p><pre>running agent....<br>Calling tool: lookup_order with input: {&#39;order_id&#39;: &#39;#4821&#39;}<br>Final Answer: Your order #4821 has been shipped and is expected to arrive on 2024-07-05 via UPS.</pre><h3>How It Works</h3><p>The agent follows a simple loop:</p><pre>┌─────────────────────────────────────────────────┐<br>│  1. Send messages (including any tool results)  │<br>│     to Claude via client.messages.create()      │<br>└───────────────────────┬─────────────────────────┘<br>                        │<br>                        ▼<br>           ┌─────────────────────┐<br>           │   response has      │<br>           │   stop_reason = ?   │<br>           └─────────┬───────────┘<br>                     │<br>         ┌───────────┴───────────┐<br>         ▼                       ▼<br>   &quot;end_turn&quot;              &quot;tool_use&quot;<br>         │                       │<br>   Return text           ┌───────┴───────┐<br>                         │ 1. Append     │<br>                         │ assistant     │<br>                         │ response      │<br>                         │ 2. Execute    │<br>                         │ each tool     │<br>                         │ 3. Append     │<br>                         │ tool_results  │<br>                         │ as user msg   │<br>                         └───────┬───────┘<br>                                 │<br>                         Loop back to top</pre><h3>Key Concepts</h3><p>ConceptExplanation<strong>tools</strong>A list of tool definitions that describes to Claude what tools exist, when to use them, and what parameters they need.<strong>stop_reason</strong>Tells you why Claude stopped generating: &quot;end_turn&quot; means the answer is ready; &quot;tool_use&quot; means Claude wants to call one or more tools.<strong>tool_use block</strong>A content block in Claude&#39;s response containing name (which tool), id (unique identifier), and input (the parameters).<strong>tool_result block</strong>A content block you send back in a user message, containing tool_use_id (matching the id from the tool_use block) and content (the tool&#39;s output).<strong>Message ordering</strong>The API requires that tool_result blocks always appear in a <strong>user</strong> message that immediately follows an <strong>assistant</strong> message containing the corresponding tool_use blocks.</p><h3>Error Categories</h3><p>When a tool fails, handle_tool_call() wraps the error with a category so Claude can react intelligently:</p><p>CategoryMeaningClaude’s likely actiontransientTemporary glitch (timeout)Wait and retrypermissionAccess deniedEscalate to humanvalidationBad parametersSelf-correct and retryinternalUnexpected bugSurface for investigation</p><h3>Customising</h3><ul><li><strong>Add more tools</strong> — Extend the tools list and add elif branches in execute_tool().</li><li><strong>Replace mock data</strong> — Swap the mock_orders dict in execute_tool() with a real database or API call.</li><li><strong>Change the model</strong> — Update the model parameter in client.messages.create() (e.g. &quot;claude-sonnet-4-20250514&quot;).</li></ul><h3>Resources</h3><ul><li><a href="https://docs.anthropic.com/en/docs/build-with-claude/tool-use">Anthropic Tool Use Documentation</a></li><li><a href="https://docs.anthropic.com/en/api/messages">Anthropic Messages API Reference</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96053157cde7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ AI Knowledge & Research Assistant With Five key AI Patterns — Chat, MCP, Prompt Engineering, RAG]]></title>
            <link>https://medium.com/@suneelr.kandali/ai-knowledge-research-assistant-2ddf0a5bae99?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ddf0a5bae99</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[multiagent-orchestration]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 17:36:29 GMT</pubDate>
            <atom:updated>2026-06-29T03:11:39.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>🤖 AI Knowledge &amp; Research Assistant With Five key AI Patterns — Chat, MCP, Prompt Engineering, RAG and Multi Agent Workflow</h3><blockquote><strong><em>A local, Ollama-powered Streamlit application</em></strong><em> that demonstrates five key AI patterns in one unified interface: conversational chat, MCP (web search), prompt engineering, RAG (Retrieval-Augmented Generation) over PDFs, and a multi-agent research workflow.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0mwaNL30iecZhrucaxLLA.png" /></figure><p>Built entirely with <strong>local models via </strong><a href="https://ollama.com/"><strong>Ollama</strong></a> — no cloud API keys required. Uses <strong>ChromaDB</strong> for vector storage, <strong>pymupdf</strong> for PDF text extraction, and <strong>Streamlit</strong> for the UI.</p><blockquote><em>⚡ </em><strong><em>Pure Python project — no LangChain, no LangGraph, no heavy AI frameworks.</em></strong><em> Just direct Ollama API calls, raw ChromaDB operations, and standard Python libraries.</em></blockquote><h3>✨ Features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvb9dAWSDBc4VdvCLvZk9w.png" /></figure><ul><li><strong>💬 AI Chat</strong> — Pure local LLM conversation without web search. Use this for general knowledge, creative tasks, or chat that doesn’t need live information.</li><li><strong>🌐 Web Search</strong> — Search DuckDuckGo and answer <strong>strictly from search results</strong>. No internal model knowledge is used.</li><li><strong>🧪 Prompt Lab</strong> — Experiment with 5 prompt templates (Beginner Explanation, Executive Summary, Detailed Analysis, Action Plan, Blog Article)</li><li><strong>📄 Chat with PDF</strong> — Upload a PDF, extract &amp; chunk its text, index into ChromaDB, then ask questions using RAG</li><li><strong>👥 Research Team</strong> — A 4-agent sequential workflow (Planner → Researcher → Writer → Reviewer) that produces a final report on any topic, optionally grounded in an uploaded PDF</li></ul><h3>📁 Project Structure</h3><pre>ai-knowledge-assistant/<br>│<br>├── app.py                       # Main Streamlit application (5 tabs)<br>├── config.py                    # Environment configuration loader<br>├── requirements.txt             # Python dependencies<br>├── .env                         # Environment variables (model names, paths)<br>│<br>├── agents/                      # Multi-agent research workflow<br>│   ├── __init__.py<br>│   └── research_team.py         # Planner, Researcher, Writer, Reviewer agents<br>│<br>├── services/                    # LLM integration &amp; web search layer<br>│   ├── __init__.py<br>│   ├── llm_service.py           # Ollama chat, generate, embed, connection check<br>│   └── web_search.py            # DuckDuckGo web search (free, no API key)<br>│<br>├── utils/                       # Utility functions<br>│   ├── __init__.py<br>│   └── pdf_utils.py             # PDF text extraction &amp; chunking<br>│<br>├── rag/                         # RAG / Vector store layer<br>│   ├── __init__.py<br>│   └── vector_store.py          # ChromaDB indexing, retrieval, formatting<br>│<br>├── prompts/                     # Prompt templates<br>│   ├── __init__.py<br>│   └── templates.py             # 5 prompt templates + builder function<br>│<br>├── data/                        # Persistent data (auto-created)<br>│   └── chroma/                  # ChromaDB persistent storage (auto-created)<br>│<br>└── README.md                    # ← You are here</pre><h3>🚀 Prerequisites</h3><p>Before you begin, ensure you have the following installed:</p><ul><li><strong>Python</strong> 3.10+ — <a href="https://www.python.org/downloads/">Download from python.org</a></li><li><strong>Ollama</strong> (latest) — <a href="https://ollama.com/download/">Download from ollama.com</a></li><li><strong>Pip</strong> — (comes bundled with Python)</li></ul><h3>Required Ollama Models</h3><p>Pull these models <strong>after</strong> installing Ollama:</p><pre># Chat model (default: gemma2:9b)<br>ollama pull gemma2:9b</pre><pre># Embedding model (used for RAG vector search)<br>ollama pull nomic-embed-text</pre><blockquote><em>You can change the models in </em><em>.env by updating </em><em>OLLAMA_CHAT_MODEL and </em><em>OLLAMA_EMBEDDING_MODEL.</em></blockquote><h3>🛠️ Setup Instructions</h3><h3>1. Clone or navigate to the project</h3><pre>git clone https://github.com/suneelkandali/ai-knowledge-assistant.git<br>cd ai-knowledge-assistant</pre><h3>2. Create and activate a virtual environment</h3><pre>python -m venv venv<br>source venv/bin/activate      # macOS / Linux<br># venv\Scripts\activate       # Windows</pre><h3>3. Install dependencies</h3><pre>pip install -r requirements.txt</pre><h3>4. Configure environment variables</h3><p>The .env file is already provided. You can adjust it as needed:</p><pre>OLLAMA_CHAT_MODEL=gemma3:4b<br>OLLAMA_EMBEDDING_MODEL=nomic-embed-text<br>CHROMA_PATH=data/chroma<br>RAG_TOP_K=4</pre><ul><li><strong>OLLAMA_CHAT_MODEL</strong> — Model used for chat, prompts, and agents (default: gemma2:9b)</li><li><strong>OLLAMA_EMBEDDING_MODEL</strong> — Model used for generating text embeddings (default: nomic-embed-text)</li><li><strong>CHROMA_PATH</strong> — Directory where ChromaDB persists vector data (default: data/chroma)</li><li><strong>RAG_TOP_K</strong> — Number of document chunks to retrieve per query (default: 4)</li></ul><h3>5. Start Ollama</h3><p>Make sure the Ollama application is running (background service). Verify it:</p><pre>ollama list</pre><p>You should see your pulled models listed.</p><h3>▶️ Running the Application</h3><h3>Start the Streamlit app</h3><pre>streamlit run app.py</pre><p>This opens your browser at http://localhost:8501 with the AI Knowledge &amp; Research Assistant interface.</p><h3>Verify Ollama connection</h3><p>In the sidebar, click <strong>“Check Ollama connection”</strong>. You should see a green success message.</p><h3>🎯 How to Use Each Tab</h3><h3>Tab 1: 💬 AI Chat</h3><p>A straightforward conversational interface with the local LLM only.</p><ol><li>Type your message in the text input and press <strong>Send</strong></li><li>The assistant responds using the configured Ollama model</li><li>The full conversation history is maintained in the session</li><li>Use the <strong>“Clear chat history”</strong> button in the sidebar to reset</li></ol><p><strong>Example prompts:</strong></p><ul><li>“Explain retrieval-augmented generation simply.”</li><li>“What are the main types of machine learning?”</li><li>“Write a short poem about artificial intelligence.”</li></ul><h3>Tab 2: 🌐 Web Search</h3><p>Searches DuckDuckGo and answers <strong>only</strong> from live web results.</p><ol><li>Type your question in the text input and press <strong>Search and answer</strong></li><li>The app searches DuckDuckGo for the latest information</li><li>The LLM answers strictly from those search results</li><li>No internal model knowledge is used</li></ol><p><strong>Best for:</strong></p><ul><li>Latest news and current events</li><li>Real-time information</li><li>Questions about recent developments</li></ul><p><strong>Example questions:</strong></p><ul><li>“What are today’s top tech headlines?”</li><li>“Latest stock market news USA”</li><li>“Current weather in New York”</li></ul><p>Experiment with different prompt engineering styles.</p><ol><li>Select a <strong>template</strong> from the dropdown (Beginner Explanation, Executive Summary, etc.)</li><li>Enter your <strong>subject or request</strong></li><li>Optionally provide <strong>additional context</strong></li><li>Click <strong>“Generate response”</strong></li></ol><p>The available templates are:</p><ul><li><strong>Beginner Explanation</strong> — Best for explaining technical concepts to non-technical audiences</li><li><strong>Executive Summary</strong> — Best for concise overviews for decision-makers</li><li><strong>Detailed Analysis</strong> — Best for in-depth examination of a topic</li><li><strong>Action Plan</strong> — Best for step-by-step implementation plans</li><li><strong>Blog Article</strong> — Best for writing educational blog content</li></ul><h3>Tab 3: 📄 Chat with PDF (RAG)</h3><p>Upload a PDF and ask questions about its content.</p><ol><li><strong>Upload a PDF</strong> using the file uploader</li><li>Wait for indexing to complete (you’ll see a success message with chunk count)</li><li>Type your question about the PDF content</li><li>The system retrieves the most relevant chunks from ChromaDB and feeds them to the LLM as context</li><li>Retrieved sources are shown below the answer</li></ol><p><strong>How it works internally:</strong></p><ol><li>PDF text is extracted page by page using pymupdf</li><li>Text is split into overlapping chunks (default: 900 chars, 150 char overlap)</li><li>Each chunk is embedded using nomic-embed-text via Ollama</li><li>Chunks + embeddings are stored in a ChromaDB collection</li><li>On each question, the query is embedded and similarity search finds the top-K chunks</li><li>Retrieved chunks are formatted as context and injected into the LLM prompt</li></ol><h3>Tab 4: 👥 Research Team (Multi-Agent)</h3><p>A sequential 4-agent research and writing workflow.</p><ol><li>Enter a <strong>research topic</strong> (e.g., “How can organizations introduce AI agents responsibly?”)</li><li>Optionally check <strong>“Use the active PDF as source context”</strong> (if you uploaded one in Tab 3)</li><li>Click <strong>“Run the four-agent team”</strong></li><li>The agents run in sequence:</li></ol><ul><li><strong>Planner Agent</strong> — Creates a research plan with objectives, questions, and structure</li><li><strong>Researcher Agent</strong> — Gathers information from the PDF context or model knowledge</li><li><strong>Writer Agent</strong> — Produces a full professional report draft</li><li><strong>Reviewer Agent</strong> — Reviews and revises the draft into the final report</li></ul><p>5. Expand each agent’s output to inspect intermediate results</p><p>6. Download the final report as a Markdown file using the <strong>“Download final report”</strong> button</p><h3>📄 File-by-File Explanation</h3><h3>Root Files</h3><h4>app.py — Main Application</h4><p>The entry point for the Streamlit app. It:</p><ul><li>Configures the page (title: “AI Knowledge and Research Assistant”, wide layout)</li><li>Initializes 4 session state variables: chat_messages, rag_collection, rag_filename, research_outputs</li><li>Builds a sidebar with configuration info (model names), connectivity check, and chat reset</li><li>Creates 4 tabs using st.tabs():</li><li><strong>Tab 1 (AI Chat):</strong> Renders chat history, accepts user input via st.form, calls generate_chat_response() and appends to session</li><li><strong>Tab 2 (Prompt Lab):</strong> Template selector dropdown, subject/context text areas, calls build_prompt() → generate_response()</li><li><strong>Tab 3 (Chat with PDF):</strong> File uploader → extract_pages_from_pdf() → chunk_pages() → index_chunks() → stores collection name; then accepts questions → retrieve_chunks() → generate_response() with context</li><li><strong>Tab 4 (Research Team):</strong> Topic input, optional PDF context checkbox, calls run_research_team(), displays expandable agent outputs, download button</li></ul><p><strong>Dependencies:</strong> All other modules in the project.</p><h4>config.py — Configuration</h4><p>Loads environment variables from .env using python-dotenv. Provides:</p><ul><li>CHAT_MODEL — Ollama model for conversation (default: gemma3:4b)</li><li>EMBEDDING_MODEL — Ollama model for embeddings (default: nomic-embed-text)</li><li>CHROMA_PATH — Pathlib Path for ChromaDB persistence (default: data/chroma)</li><li>RAG_TOP_K — Number of chunks to retrieve (default: 4)</li></ul><p>Automatically creates the ChromaDB directory if it doesn’t exist.</p><h4>requirements.txt — Dependencies</h4><pre>streamlit<br>ollama<br>pymupdf<br>chromadb<br>python-dotenv</pre><blockquote><em>⚡ </em><strong><em>Zero AI framework dependencies.</em></strong><em> No LangChain, LangGraph, or similar — just the Ollama Python SDK, raw ChromaDB, and standard Python libraries.</em></blockquote><ul><li><strong>streamlit</strong> — Web UI framework</li><li><strong>duckduckgo_search</strong> — Free web search (no API key needed) for live chat answers</li><li><strong>ollama</strong> — Python client for local Ollama server</li><li><strong>pymupdf</strong> — PDF text extraction (MuPDF bindings)</li><li><strong>chromadb</strong> — Vector database for RAG</li><li><strong>python-dotenv</strong> — Load .env file into environment</li></ul><h4>.env — Environment Variables</h4><pre>OLLAMA_CHAT_MODEL=llama3.1<br>OLLAMA_EMBEDDING_MODEL=nomic-embed-text<br>CHROMA_PATH=data/chroma<br>RAG_TOP_K=4</pre><blockquote><strong><em>Note:</em></strong><em> </em><em>.env is excluded from version control (add to </em><em>.gitignore). It contains only local configuration — no secrets, since everything runs locally.</em></blockquote><h3>agents/ — Multi-Agent Research Workflow</h3><h4>agents/research_team.py — Research Team Agents</h4><p>Implements a <strong>sequential multi-agent workflow</strong> with 4 specialized agents:</p><ul><li><strong>Planner</strong> — Creates a research plan (objectives, questions, structure, risks) — temperature: 0.1 — <em>“You are the Planner Agent. Decompose topics into logical and useful plans.”</em></li><li><strong>Researcher</strong> — Gathers information from PDF context or model knowledge — temperature: 0.2 — <em>“You are the Researcher Agent. Gather and organize reliable material for the Writer Agent.”</em></li><li><strong>Writer</strong> — Produces a professional report (title, summary, findings, examples, recommendations) — temperature: 0.3 — <em>“You are the Writer Agent. Turn research notes into a clear and useful report.”</em></li><li><strong>Reviewer</strong> — Reviews and revises the draft (accuracy, consistency, readability, uncertainty) — temperature: 0.1 — <em>“You are the Reviewer Agent. Produce the strongest and most responsible final version.”</em></li></ul><p><strong>Key function:</strong> run_research_team(topic, source_context) runs all 4 agents sequentially.</p><h3>services/ — LLM Integration Layer</h3><h4>services/llm_service.py — LLM Service</h4><p>The sole interface to Ollama. Provides 4 functions:</p><ul><li><strong>generate_response(prompt, system_prompt, temperature)</strong> — Single-turn prompt → response using CHAT_MODEL</li><li><strong>generate_chat_response(history, system_prompt)</strong> — Multi-turn chat with history using CHAT_MODEL</li><li><strong>embed_texts(texts)</strong> — Batch text → embedding vectors using EMBEDDING_MODEL</li><li><strong>check_ollama_connection()</strong> — Verify Ollama is reachable by calling ollama.list()</li></ul><p>All functions include error handling that raises RuntimeError with actionable messages.</p><h4>services/web_search.py — Web Search Service</h4><p>Free web search using DuckDuckGo — no API key required. Used by the AI Chat tab when web search is enabled.</p><p><strong>search_web(query, max_results=5, region=&quot;wt-wt&quot;)</strong> — Performs a web search and returns a list of dicts with title, url, and snippet.</p><p><strong>format_search_results(results)</strong> — Converts raw search results into a numbered text block for LLM context.</p><p><strong>build_web_search_context(query, max_results=5)</strong> — Convenience function that searches and returns a ready-to-use context string with a source label. Returns an empty string on failure.</p><h3>utils/ — Utility Functions</h3><h4>utils/pdf_utils.py — PDF Utilities</h4><p><strong>extract_pages_from_pdf(pdf_bytes)</strong> — Opens PDF from bytes using pymupdf, extracts text page by page. Returns list[PageText].</p><p><strong>chunk_pages(pages, chunk_size=900, overlap=150)</strong> — Splits page text into overlapping chunks. Returns list[TextChunk].</p><h3>rag/ — Vector Store &amp; RAG Layer</h3><h4>rag/vector_store.py — Vector Store</h4><p><strong>_client()</strong> — Creates ChromaDB persistent client at CHROMA_PATH.</p><p><strong>make_collection_name(filename, file_bytes)</strong> — Creates unique collection name via SHA-256 hash.</p><p><strong>index_chunks(collection_name, chunks, source_name, batch_size=32)</strong> — Deletes old collection, creates new one, batches chunks + embeddings, adds to ChromaDB.</p><p><strong>retrieve_chunks(collection_name, question, top_k=4)</strong> — Embeds query, searches ChromaDB, returns ranked chunks with metadata.</p><p><strong>format_retrieved_context(retrieved)</strong> — Formats chunks as [Source N: file, page X] blocks for LLM consumption.</p><h3>prompts/ — Prompt Templates</h3><h4>prompts/templates.py — Prompt Templates</h4><p>5 curated templates: Beginner Explanation, Executive Summary, Detailed Analysis, Action Plan, Blog Article.</p><p><strong>build_prompt(template_name, subject, context=&quot;&quot;)</strong> — Returns (system_prompt, user_prompt) tuple.</p><h3>Testing</h3><h3>Manual Testing (Streamlit UI)</h3><pre>streamlit run app.py<br># Tab 1: Type a message and verify response<br># Tab 2: Try each template with a subject<br># Tab 3: Upload a PDF, ask a question<br># Tab 4: Enter topic, run the 4-agent team</pre><h3>Script-level Testing</h3><pre># Test Ollama connection<br>python -c &quot;from services.llm_service import check_ollama_connection; print(check_ollama_connection())&quot;</pre><pre># Test config<br>python -c &quot;from config import CHAT_MODEL; print(f&#39;Model: {CHAT_MODEL}&#39;)&quot;</pre><h3>Troubleshooting</h3><ul><li><strong>Ollama could not be reached</strong> — Ollama not running → Start Ollama or run ollama serve</li><li><strong>model not found</strong> — Model not pulled → Run ollama pull gemma2:9b</li><li><strong>No selectable text</strong> — PDF is scanned → Use OCR or a text-based PDF</li><li><strong>Slow responses</strong> — Large model → Switch to smaller model in .env</li></ul><h3>Architecture Diagram</h3><pre>Streamlit UI (app.py) ─── 4 Tabs<br>    │<br>    ├── Tab 1: AI Chat ──────── llm_service.py (ollama.chat)<br>    ├── Tab 2: Web Search ──────── Web Search<br>    ├── Tab 3: Prompt Lab ───── templates.py + llm_service.py<br>    ├── Tab 4: Chat w/ PDF ──── pdf_utils.py → vector_store.py → llm_service.py<br>    └── Tab 5: Research Team ── research_team.py (4 agents) → llm_service.py</pre><h3>Learning Path</h3><ol><li><strong>AI Chat</strong> — Basic LLM interaction</li><li><strong>Web Search</strong> — MCP Integration</li><li><strong>Prompt Lab</strong> — Prompt engineering</li><li><strong>Chat with PDF</strong> — RAG fundamentals</li><li><strong>Research Team</strong> — Multi-agent workflows</li></ol><h3>License</h3><p>Educational purposes only. All rights reserved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ddf0a5bae99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Microservices with Istio Service Mesh: Theory and hands-on POC — Part 2]]></title>
            <link>https://medium.com/@suneelr.kandali/securing-microservices-with-istio-service-mesh-theory-and-hands-on-poc-part-2-d671f8f5a8b7?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/d671f8f5a8b7</guid>
            <category><![CDATA[istio-service-mesh]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[microservices-security]]></category>
            <category><![CDATA[gke]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 12:51:38 GMT</pubDate>
            <atom:updated>2026-06-22T12:51:38.391Z</atom:updated>
            <content:encoded><![CDATA[<p>A complete, production-ready, end-to-end guide to creating, deploying, securing with mTLS (via GKE’s managed Service Mesh/Istio), testing, and cleaning up a polyglot microservices architecture.</p><blockquote><strong><em>⚠️ Important Note for Readers:</em></strong><em> Terminal commands in this guide are tailored for </em><strong><em>macOS</em></strong><em>. If you are on </em><strong><em>Windows</em></strong><em> or </em><strong><em>Linux</em></strong><em>, you may need to adjust commands (e.g., use PowerShell equivalents or package managers like </em><em>apt instead of </em><em>brew).</em></blockquote><h3>Architecture Overview</h3><pre>┌─────────────────────────────────────────────────────────────┐<br>│                    GKE Cluster                              │<br>│                  Namespace: secure-mesh                     │<br>│                                                             │<br>│  ┌──────────────────┐         ┌──────────────────┐          │<br>│  │  Spring Boot API  │ ──────▶│  Node.js API     │          │<br>│  │   (Port 8080)     │  mTLS  │   (Port 3000)    │          │<br>│  │                    │◀────── │                   │        │<br>│  └──────────────────┘         └──────────────────┘          │<br>│         │                                │                  │<br>│         ▼                                ▼                  │<br>│  ┌──────────────┐              ┌──────────────┐             │<br>│  │ Istio Sidecar │              │ Istio Sidecar │           │<br>│  │   (Envoy)     │              │   (Envoy)     │           │<br>│  └──────────────┘              └──────────────┘             │<br>└─────────────────────────────────────────────────────────────┘</pre><p>A complete guide to deploying <strong>two microservices</strong> (Spring Boot + Node.js) on <strong>Google Kubernetes Engine (GKE)</strong> with <strong>Istio service mesh</strong> for mTLS encryption and fine-grained access control. The Spring Boot service calls the Node.js service via Kubernetes internal DNS, with all traffic secured through Istio’s mutual TLS (mTLS).</p><h3>Key Concepts</h3><ul><li><strong>Istio Sidecar Injection</strong> — Automatically adds an Envoy proxy container to each pod, intercepting all network traffic</li><li><strong>mTLS (mutual TLS)</strong> — Both client and server authenticate each other using certificates, encrypting all traffic</li><li><strong>PeerAuthentication</strong> — Istio resource that defines the mTLS mode (STRICT, PERMISSIVE, DISABLE) for a namespace or workload</li><li><strong>AuthorizationPolicy</strong> — Istio resource that defines fine-grained access control rules (who can call which service)</li><li><strong>ClusterIP Service</strong> — Kubernetes service type that exposes the service only within the cluster (no external access)</li><li><strong>Kubernetes DNS</strong> — Services are reachable via &lt;service-name&gt;.&lt;namespace&gt;.svc.cluster.local:&lt;port&gt;</li></ul><h3>Tech Stack</h3><ul><li><strong>Cloud Provider</strong> — Google Cloud Platform (GCP)</li><li><strong>Container Orchestration</strong> — Google Kubernetes Engine (GKE)</li><li><strong>Service Mesh</strong> — Istio 1.30.1</li><li><strong>Frontend API</strong> — Spring Boot 3.2.5 (Java 17)</li><li><strong>Backend API</strong> — Node.js 18.x / Express 4.19.2</li><li><strong>Container Registry</strong> — Google Container Registry (GCR)</li><li><strong>Security</strong> — Istio mTLS STRICT + AuthorizationPolicy</li></ul><h3>What You Will Do</h3><ol><li>Install the required local tools (gcloud, kubectl, docker)</li><li>Clone the repository from GitHub</li><li>Authenticate to Google Cloud and create a project</li><li>Enable all required GCP APIs (GKE, Container Registry, Istio mesh, logging, monitoring)</li><li>Create a GKE cluster, build Docker images, update manifests, and deploy services</li><li>Enforce mTLS STRICT mode for all pod-to-pod communication</li><li>Verify that inter-service communication works through the mesh</li><li>Clean up all cloud resources</li></ol><h3>Prerequisites</h3><p>Before you begin, ensure the following tools are installed:</p><ul><li><strong>Google Cloud SDK (</strong><strong>gcloud)</strong> — GCP authentication &amp; project management → <a href="https://cloud.google.com/sdk/docs/install">Install Guide</a></li><li><strong>kubectl</strong> — Kubernetes CLI → gcloud components install kubectl</li><li><strong>docker</strong> — Build container images → <a href="https://docs.docker.com/get-docker/">Install Docker</a></li></ul><p>Verify your installations:</p><pre>gcloud --version<br>kubectl version --client<br>docker --version</pre><h3>Placeholders</h3><p>Throughout this guide, replace the following placeholders with your actual values:</p><ul><li><strong>&lt;YOUR_GCP_PROJECT_ID&gt;</strong> — Your Google Cloud project ID (must be globally unique, lowercase letters/digits/hyphens only) → e.g. gke-mtls-mesh-demo</li><li><strong>&lt;YOUR_PROJECT_NAME&gt;</strong> — A human-readable display name for your project (your choice) → e.g. GKE mTLS Mesh Demo</li><li><strong>&lt;YOUR_REGION&gt;</strong> — GCP region for the GKE cluster → e.g. us-central1</li><li><strong>&lt;YOUR_ZONE&gt;</strong> — GCP zone for the GKE cluster → e.g. us-central1-a</li><li><strong>&lt;CLUSTER_NAME&gt;</strong> — Name of your GKE cluster → e.g. mesh-demo-cluster</li></ul><blockquote><strong><em>Important:</em></strong><em> The </em><em>&lt;YOUR_GCP_PROJECT_ID&gt; must be replaced consistently in </em><strong><em>all</em></strong><em> commands and </em><strong><em>all</em></strong><em> files (</em><em>k8s/manifests.yaml, Docker build/push commands, cleanup commands) throughout this guide.</em></blockquote><blockquote><strong><em>Tip:</em></strong><em> You can check your current project with </em><em>gcloud config get-value project.</em></blockquote><h3>Project Structure</h3><pre>gke-microservices-servicesmesh-poc/<br>├── k8s/<br>│   ├── manifests.yaml          # Namespace, Deployments &amp; Services<br>│   └── mesh-security.yaml      # Istio PeerAuthentication &amp; AuthorizationPolicy<br>├── nodejs-service/<br>│   ├── Dockerfile              # Multi-stage Node.js 18 build<br>│   ├── index.js                # Express.js API (port 3000)<br>│   └── package.json            # Node.js dependencies<br>├── springboot-service/<br>│   ├── Dockerfile              # Multi-stage Maven + JDK 17 build<br>│   ├── pom.xml                 # Spring Boot 3.2.5 dependencies<br>│   └── src/main/java/com/example/demo/<br>│       └── DemoApplication.java # Spring Boot app + REST controller (port 8080)<br>└── .gitignore</pre><h3>Step-by-Step Guide</h3><h3>Step 1 — Clone the Repository</h3><p>Clone the project from GitHub:</p><pre>git clone https://github.com/suneelkandali/gke-microservices-servicesmesh-poc.git</pre><p>Navigate into the project root directory. <strong>All subsequent commands in this guide should be run from this directory:</strong></p><pre>cd gke-microservices-servicesmesh-poc</pre><p>Verify the project structure:</p><pre>ls -la</pre><p>You should see the following directories and files:</p><pre>k8s/<br>nodejs-service/<br>springboot-service/<br>README.md</pre><h3>Step 2 — Authenticate to Google Cloud and Create a Project</h3><p>Log in to Google Cloud:</p><pre>gcloud auth login</pre><p>Create a new GCP project. The project name is <strong>your choice</strong> — pick any unique name that makes sense for you:</p><pre>gcloud projects create &lt;YOUR_GCP_PROJECT_ID&gt; --name=&quot;&lt;YOUR_PROJECT_NAME&gt;&quot;</pre><blockquote><strong><em>Note:</em></strong><em> Replace </em><em>&lt;YOUR_GCP_PROJECT_ID&gt; with a globally unique project ID (e.g. </em><em>my-gke-mesh-demo) and </em><em>&lt;YOUR_PROJECT_NAME&gt; with a human-readable display name (e.g. </em><em>GKE mTLS Mesh Demo). The project ID must be unique across all of Google Cloud and can only contain lowercase letters, digits, and hyphens.</em></blockquote><p>Set the new project as your active project:</p><pre>gcloud config set project &lt;YOUR_GCP_PROJECT_ID&gt;</pre><p>Verify your active account and project:</p><pre>gcloud auth list<br>gcloud config get-value project</pre><h3>Step 3 — Enable Required APIs</h3><p>Enable all the GCP APIs required for GKE, Container Registry, and Istio service mesh:</p><pre># GKE and Container Registry<br>gcloud services enable container.googleapis.com<br>gcloud services enable containerregistry.googleapis.com<br># Istio Service Mesh support<br>gcloud services enable meshconfig.googleapis.com<br>gcloud services enable meshtelemetry.googleapis.com<br># Logging and Monitoring (required for Istio telemetry)<br>gcloud services enable logging.googleapis.com<br>gcloud services enable monitoring.googleapis.com<br># Resource Manager and IAM (required for cluster and mesh operations)<br>gcloud services enable cloudresourcemanager.googleapis.com<br>gcloud services enable iam.googleapis.com</pre><blockquote><strong><em>Note:</em></strong><em> The </em><em>meshconfig.googleapis.com API is essential for GKE to manage Istio configuration and sidecar injection. The </em><em>meshtelemetry.googleapis.com API enables Istio metrics collection for observability.</em></blockquote><p>Verify that all APIs are enabled:</p><pre>gcloud services list --enabled --filter=&quot;name:container.googleapis.com OR name:containerregistry.googleapis.com OR name:meshconfig.googleapis.com OR name:meshtelemetry.googleapis.com OR name:logging.googleapis.com OR name:monitoring.googleapis.com&quot;</pre><h3>Step 4 — Create GKE Cluster, Build Images, Update Manifests, and Deploy Services</h3><p>This step covers the complete flow from cluster creation to deployment. Follow the sub-steps in order.</p><h4>4a — Create the GKE Cluster</h4><p>Create a standard GKE cluster:</p><pre>gcloud container clusters create &lt;CLUSTER_NAME&gt; \<br>  --zone &lt;YOUR_ZONE&gt; \<br>  --num-nodes=3 \<br>  --machine-type=e2-standard-2 \<br>  --release-channel=regular</pre><p>Get credentials for kubectl:</p><pre>gcloud container clusters get-credentials &lt;CLUSTER_NAME&gt; \<br>  --zone &lt;YOUR_ZONE&gt; \<br>  --project &lt;YOUR_GCP_PROJECT_ID&gt;</pre><p>Verify the cluster is running:</p><pre>kubectl get nodes</pre><h4>4b — Create the Kubernetes Namespace</h4><p>Create the secure-mesh namespace with Istio sidecar injection enabled:</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: secure-mesh<br>  labels:<br>    istio-injection: enabled<br>EOF</pre><blockquote><em>The </em><em>istio-injection: enabled label tells Istio to automatically inject an Envoy sidecar proxy into every pod deployed in this namespace.</em></blockquote><h4>4c — Build and Push Docker Images</h4><p><strong>Configure Docker for GCR:</strong></p><pre>gcloud auth configure-docker</pre><p><strong>Build and Push the Node.js Service Image:</strong></p><pre>cd nodejs-service</pre><pre>docker build -t gcr.io/&lt;YOUR_GCP_PROJECT_ID&gt;/nodejs-service:1.0.0 .</pre><pre>docker push gcr.io/&lt;YOUR_GCP_PROJECT_ID&gt;/nodejs-service:1.0.0</pre><pre>cd ..</pre><p><strong>Node.js Dockerfile:</strong></p><pre>FROM node:18-slim<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install --production<br>COPY index.js .<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><p><strong>Build and Push the Spring Boot Service Image:</strong></p><pre>cd springboot-service</pre><pre>docker build -t gcr.io/&lt;YOUR_GCP_PROJECT_ID&gt;/springboot-service:1.0.0 .</pre><pre>docker push gcr.io/&lt;YOUR_GCP_PROJECT_ID&gt;/springboot-service:1.0.0</pre><pre>cd ..</pre><p><strong>Spring Boot Dockerfile (multi-stage build):</strong></p><pre>FROM maven:3.8.5-openjdk-17 AS build<br>WORKDIR /app<br>COPY pom.xml .<br>COPY src ./src<br>RUN mvn clean package -DskipTests</pre><pre>FROM eclipse-temurin:17-jre-jammy<br>WORKDIR /app<br>COPY --from=build /app/target/springboot-service-0.0.1-SNAPSHOT.jar app.jar<br>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><h4>4d — Update Manifests and Deploy Services</h4><p>Update the image references in k8s/manifests.yaml with your actual GCP project ID:</p><pre># In k8s/manifests.yaml, replace the image paths:<br><br>image: gcr.io/&lt;YOUR_GCP_PROJECT_ID&gt;/springboot-service:1.0.0<br># ... and ...<br>image: gcr.io/&lt;YOUR_GCP_PROJECT_ID&gt;/nodejs-service:1.0.0</pre><p>Apply the Kubernetes manifests:</p><pre>kubectl apply -f k8s/manifests.yaml</pre><p>This creates:</p><ul><li><strong>Namespace:</strong> secure-mesh (with Istio sidecar injection enabled)</li><li><strong>Spring Boot Deployment</strong> (1 replica) + <strong>Service</strong> (ClusterIP, port 8080)</li><li><strong>Node.js Deployment</strong> (1 replica) + <strong>Service</strong> (ClusterIP, port 3000)</li></ul><p>Verify the deployments:</p><pre>kubectl get all -n secure-mesh</pre><p>Wait until both pods show READY 2/2 (the second container is the Istio Envoy sidecar):</p><pre>kubectl get pods -n secure-mesh -w</pre><blockquote><strong><em>Note:</em></strong><em> You should see </em><em>2/2 under READY for each pod — this confirms the Istio sidecar proxy has been injected alongside your application container.</em></blockquote><h3>Step 5 — Enforce mTLS STRICT Mode</h3><p>Apply the Istio PeerAuthentication policy to enforce mutual TLS across the entire namespace:</p><pre>kubectl apply -f k8s/mesh-security.yaml</pre><p>This file contains two resources:</p><p><strong>PeerAuthentication (mTLS STRICT):</strong></p><pre>apiVersion: security.istio.io/v1<br>kind: PeerAuthentication<br>metadata:<br>  name: default<br>  namespace: secure-mesh<br>spec:<br>  mtls:<br>    mode: STRICT</pre><blockquote><em>In </em><em>STRICT mode, all pod-to-pod communication within the namespace </em><strong><em>must</em></strong><em> use mTLS. Plain-text connections are immediately rejected at the Envoy proxy sidecar boundary.</em></blockquote><p><strong>AuthorizationPolicy (Service-to-Service Access Control):</strong></p><pre>apiVersion: security.istio.io/v1<br>kind: AuthorizationPolicy<br>metadata:<br>  name: nodejs-policy<br>  namespace: secure-mesh<br>spec:<br>  selector:<br>    matchLabels:<br>      app: nodejs-service<br>  action: ALLOW<br>  rules:<br>  - from:<br>    - source:<br>        principals: [&quot;cluster.local/ns/secure-mesh/sa/default&quot;]</pre><blockquote><em>This policy ensures that </em><strong><em>only</em></strong><em> the Spring Boot service (via the </em><em>default service account in the </em><em>secure-mesh namespace) can reach the Node.js service. All other traffic sources are denied.</em></blockquote><h3>Step 6 — Verify the Setup</h3><h4>6a — Test Node.js Service Call from Spring Boot</h4><p>First, verify that the Spring Boot service can reach the Node.js service from <strong>within the cluster</strong> using kubectl exec:</p><pre>kubectl exec -it deploy/springboot-deploy -n secure-mesh -c springboot -- \<br>  curl http://nodejs-service.secure-mesh.svc.cluster.local:3000/ --max-time 5</pre><p><strong>Expected output:</strong></p><pre>{&quot;service&quot;:&quot;nodejs-service&quot;,&quot;status&quot;:&quot;ok&quot;}</pre><blockquote><em>This confirms that the Spring Boot pod can resolve the Node.js service via Kubernetes DNS (</em><em>nodejs-service.secure-mesh.svc.cluster.local) and receive a response over the Istio service mesh.</em></blockquote><p>Next, test the Spring Boot /invoke-backend endpoint which internally calls the Node.js service and returns a combined response:</p><pre>kubectl exec -it deploy/springboot-deploy -n secure-mesh -c springboot -- \<br>  curl http://localhost:8080/invoke-backend --max-time 5</pre><p><strong>Expected output:</strong></p><pre>Spring Boot received: {&quot;service&quot;:&quot;nodejs-service&quot;,&quot;status&quot;:&quot;ok&quot;}</pre><blockquote><em>This confirms the full chain: Spring Boot receives the request → calls Node.js via </em><em>http://nodejs-service.secure-mesh.svc.cluster.local:3000/data → returns the combined response.</em></blockquote><h4>6b — Test from Your Local Machine (via Port-Forward)</h4><p>Port-forward the Spring Boot service to your local machine:</p><pre>kubectl port-forward svc/springboot-service 8080:8080 -n secure-mesh</pre><p>In a new terminal, invoke the backend:</p><pre>curl http://localhost:8080/invoke-backend</pre><p><strong>Expected output:</strong></p><pre>Spring Boot received: {&quot;service&quot;:&quot;nodejs-service&quot;,&quot;status&quot;:&quot;ok&quot;}</pre><p>This confirms that:</p><ul><li>✅ Spring Boot is running and healthy</li><li>✅ Spring Boot can reach Node.js via Kubernetes DNS (http://nodejs-service.secure-mesh.svc.cluster.local:3000/data)</li><li>✅ Istio mTLS is working (traffic between services is encrypted)</li></ul><h4>6c — Verify mTLS is Enforced</h4><p>Exec into a pod and attempt a plain-text (non-mTLS) connection to the Node.js service:</p><pre>kubectl exec -it deploy/springboot-deploy -n secure-mesh -c springboot -- \<br>  curl http://nodejs-service.secure-mesh.svc.cluster.local:3000/ --max-time 5</pre><blockquote><em>If mTLS is working correctly, the request should succeed because it goes through the Envoy sidecar (which handles mTLS automatically).</em></blockquote><h4>6d — Test Node.js Service from a Different Namespace</h4><p>To verify that the AuthorizationPolicy blocks unauthorized cross-namespace access, launch a temporary test pod in the default namespace and attempt to reach the Node.js service:</p><pre>kubectl run test-client --image=curlimages/curl --rm -it --restart=Never -n default -- \<br>  curl http://nodejs-service.secure-mesh.svc.cluster.local:3000/ --max-time 5</pre><p><strong>Expected output:</strong></p><pre>command terminated with exit code 7<br>curl: (7) Failed to connect to nodejs-service.secure-mesh.svc.cluster.local port 3000: Connection refused</pre><blockquote><em>The connection is </em><strong><em>blocked</em></strong><em> because the </em><em>AuthorizationPolicy on the Node.js service only allows traffic from the </em><em>default service account within the </em><em>secure-mesh namespace. A pod in the </em><em>default namespace does not match the allowed principal (</em><em>cluster.local/ns/secure-mesh/sa/default), so the request is denied by the Envoy sidecar proxy.</em></blockquote><p>This confirms that:</p><ul><li>✅ The AuthorizationPolicy is working correctly</li><li>✅ The Node.js service is protected from unauthorized cross-namespace access</li><li>✅ Only the Spring Boot service within secure-mesh can reach the Node.js service</li></ul><h4>6e — Check Istio Configuration</h4><p>Verify the mTLS status:</p><pre>istioctl x describe pod &lt;POD_NAME&gt; -n secure-mesh</pre><p>Check proxy configuration:</p><pre>istioctl proxy-status</pre><p>View the AuthorizationPolicy:</p><pre>kubectl get authorizationpolicy -n secure-mesh<br>kubectl describe authorizationpolicy nodejs-policy -n secure-mesh</pre><p>View the PeerAuthentication:</p><pre>kubectl get peerauthentication -n secure-mesh<br>kubectl describe peerauthentication default -n secure-mesh</pre><h3>Step 7 — Inspect Sidecar Logs</h3><p>To confirm the Istio sidecar is active, check the logs:</p><pre># Application logs<br>kubectl logs deploy/springboot-deploy -n secure-mesh -c springboot</pre><pre># Istio sidecar (Envoy proxy) logs<br>kubectl logs deploy/springboot-deploy -n secure-mesh -c istio-proxy</pre><h3>Step 8 — Clean Up Resources</h3><p>Follow these sub-steps in order to remove all cloud resources and avoid ongoing charges.</p><h4>8a — Delete Kubernetes Resources</h4><p>Delete the secure-mesh namespace, which removes all deployments, services, and Istio policies:</p><pre>kubectl delete namespace secure-mesh</pre><p>Verify all resources are removed:</p><pre>kubectl get namespaces</pre><blockquote><em>The </em><em>secure-mesh namespace should no longer appear in the list.</em></blockquote><h4>8b — Delete the GKE Cluster</h4><p>Delete the GKE cluster to stop all compute charges:</p><pre>gcloud container clusters delete &lt;CLUSTER_NAME&gt; \<br>  --zone &lt;YOUR_ZONE&gt; \<br>  --project &lt;YOUR_GCP_PROJECT_ID&gt;</pre><p>Verify the cluster is deleted:</p><pre>gcloud container clusters list --project &lt;YOUR_GCP_PROJECT_ID&gt;</pre><blockquote><em>The cluster should no longer appear in the list.</em></blockquote><h4>8c — Delete Container Images from GCR (Optional)</h4><p>Remove the Docker images pushed to Google Container Registry:</p><pre>gcloud container images delete gcr.io/&lt;YOUR_GCP_PROJECT_ID&gt;/springboot-service:1.0.0 --force-delete-tags<br>gcloud container images delete gcr.io/&lt;YOUR_GCP_PROJECT_ID&gt;/nodejs-service:1.0.0 --force-delete-tags</pre><h4>8d — Delete the GCP Project (Optional)</h4><p>If you no longer need the project, delete it entirely to stop all billing:</p><pre>gcloud projects delete &lt;YOUR_GCP_PROJECT_ID&gt;</pre><blockquote><strong><em>Warning:</em></strong><em> This permanently deletes the project and all its resources. Only do this if you are sure you no longer need it.</em></blockquote><p>Verify the project is deleted:</p><pre>gcloud projects list --filter=&quot;projectId:&lt;YOUR_GCP_PROJECT_ID&gt;&quot;</pre><h3>Troubleshooting</h3><h3>Pod stuck in Pending or CrashLoopBackOff</h3><pre>kubectl describe pod &lt;POD_NAME&gt; -n secure-mesh<br>kubectl logs &lt;POD_NAME&gt; -n secure-mesh</pre><p>Common causes:</p><ul><li>Image pull errors → Verify the image exists in GCR and the project ID is correct</li><li>Insufficient resources → Check node capacity with kubectl describe nodes</li></ul><h3>Istio sidecar not injected (pod shows 1/2 READY)</h3><pre>kubectl get namespace secure-mesh --show-labels</pre><p>Ensure the namespace has istio-injection=enabled. If not, label it:</p><pre>kubectl label namespace secure-mesh istio-injection=enabled</pre><p>Then restart the deployments:</p><pre>kubectl rollout restart deployment -n secure-mesh</pre><h3>Connection refused between services</h3><pre># Verify services exist and have endpoints<br>kubectl get svc -n secure-mesh<br>kubectl get endpoints -n secure-mesh</pre><pre># Check if AuthorizationPolicy is blocking traffic<br>kubectl logs deploy/nodejs-deploy -n secure-mesh -c istio-proxy | grep -i deny</pre><h3>curl fails from outside the mesh</h3><p>This is expected. When mTLS is set to STRICT, external plain-text connections are rejected. Always test inter-service communication from within the mesh (via kubectl exec or kubectl port-forward).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d671f8f5a8b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Microservices with Istio Service Mesh: Theory and hands-on POC — Part 1]]></title>
            <link>https://medium.com/@suneelr.kandali/securing-microservices-with-istio-service-mesh-theory-and-hands-on-poc-b3e78556dc5f?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3e78556dc5f</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[microservices-security]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[istio-service-mesh]]></category>
            <category><![CDATA[sre]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 21:07:09 GMT</pubDate>
            <atom:updated>2026-06-22T12:53:18.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6QNFXAEl_n-Zp1YpwyPsg.png" /></figure><p>At its core, <strong>Istio</strong> is an open-source <strong>service mesh</strong> — a dedicated infrastructure layer designed to control, secure, and observe how microservices communicate with one another.</p><p><strong>Istio is almost never critical on day one, but it can become absolutely mission-critical as your organization and microservices architecture scale.</strong> Kubernetes handles container orchestration (deploying, scaling, and basic service discovery) incredibly well. However, it treats the network like a pipe — it doesn’t naturally care about <em>what</em> is traveling through that pipe. Istio steps in to manage, secure, and observe the actual traffic between those containers.</p><p>To determine if Istio is critical for your specific workloads, evaluate where your team lands across three main pillars: <strong>Security</strong>, <strong>Traffic Control</strong>, and <strong>Observability</strong>.</p><h3>1. Zero-Trust Security &amp; Compliance</h3><p><strong>When it becomes critical:</strong> You operate in a highly regulated industry (FinTech, HealthTech) or follow strict Zero-Trust security models.</p><ul><li><strong>What K8s gives you natively:</strong> basic Network Policies that block or allow traffic based on IP addresses and ports (Layer 3/4). It does not natively encrypt traffic between pods or validate application identities.</li><li><strong>What Istio adds:</strong> Out-of-the-box <strong>mutual TLS (mTLS)</strong>. It automatically issues certificates to your pods, rotates them, and ensures all pod-to-pod communication is strongly authenticated and encrypted. It also lets you build Layer 7 Authorization Policies (e.g., “Only the Frontend service can issue a POST request to the /payments endpoint of the Backend service&quot;).</li></ul><blockquote><strong><em>Verdict:</em></strong><em> If you need end-to-end encryption in transit and strict identity-based access control without forcing developers to write custom cryptographic code into every single microservice, Istio is highly critical.</em></blockquote><h3>2. Advanced Traffic Management</h3><p><strong>When it becomes critical:</strong> You have complex deployment strategies, strict uptime SLAs, or need to manage cross-cluster/hybrid-cloud traffic.</p><ul><li><strong>What K8s gives you natively:</strong> kube-proxy, which load-balances traffic evenly using round-robin at the connection level. Native canary deployments in K8s are crude (e.g., if you want a 5% canary rollout, you have to spin up 19 replicas of V1 and 1 replica of V2).</li><li><strong>What Istio adds:</strong> Intelligent, application-aware routing. You can split traffic exactly by percentage (e.g., sending exactly 1% of traffic to V2), or route based on HTTP headers (e.g., “Send requests where header[user-type] == beta to V2&quot;). It also provides instant network resilience features like circuit breaking, retries, and rate-limiting.</li></ul><blockquote><strong><em>Verdict:</em></strong><em> If your team struggles with risky deployments, or if your applications frequently cascade-fail because one downstream service got slow, Istio’s traffic controls become vital.</em></blockquote><h3>3. Deep Observability</h3><p><strong>When it becomes critical:</strong> You have dozens or hundreds of microservices, and tracking down “why is this API call slow?” feels like finding a needle in a haystack.</p><ul><li><strong>What K8s gives you natively:</strong> Basic container logs and resource metrics (CPU/Memory utilization via Metrics Server). It won’t tell you HTTP error rates or service-to-service latency.</li><li><strong>What Istio adds:</strong> Because Istio intercepts all network traffic, it automatically generates massive amounts of telemetry (golden signals: latency, traffic volume, errors, saturation) and distributed tracing data without changing a single line of application code. Tools like Kiali can read this to draw a live, real-time map of how your services interact.</li></ul><blockquote><strong><em>Verdict:</em></strong><em> If your developers spend hours in post-mortems arguing over </em>which<em> service caused a latency spike, Istio’s telemetry is a lifesaver.</em></blockquote><h3>The Catch: Why You Might Not Want It</h3><p>Before adopting Istio, you have to weigh its benefits against its steep costs:</p><ul><li><strong>Operational Complexity:</strong> Istio is a beast to manage. It introduces custom resources (VirtualServices, DestinationRules, Gateways) that your platform team must learn and maintain.</li><li><strong>Resource Overhead:</strong> Traditionally, Istio injects an Envoy “sidecar” proxy into every single pod. If you have 500 pods, that’s 500 extra proxies consuming CPU and memory. <em>(Note: Istio’s newer </em><strong><em>Ambient Mode</em></strong><em> solves this by offering a sidecarless architecture, significantly lowering resource costs).</em></li><li><strong>Latency Tax:</strong> Forcing traffic through proxies adds a small amount of millisecond-level overhead to every network hop.</li></ul><p>Here is exactly how the lifecycle works during an mTLS call from <strong>Service A</strong> to <strong>Service B</strong>:</p><h3>The mTLS Traffic Lifecycle</h3><pre>[ Pod A ]                                       [ Pod B ]<br>+---------------+                               +---------------+<br>| Application A | --( Plain HTTP/1.1 )-------&gt;  |  Envoy Proxy  | (Sidecar)<br>+---------------+                               +---------------+<br>        |                                               |<br>        v                                               v<br>+---------------+                               +---------------+<br>|  Envoy Proxy  | (Sidecar)                     | Application B |<br>+---------------+                               +---------------+<br>        |                                               ^<br>        |=======( Encrypted mTLS over Wire )============|</pre><h3>1. Egress (Leaving the Source)</h3><ul><li><strong>Application A</strong> sends a standard, unencrypted HTTP request (e.g., GET /api/data) destined for Service B.</li><li>Istio’s networking rules (via iptables) intercept this traffic and redirect it into the <strong>Envoy proxy sidecar</strong> running inside Pod A.</li><li>The Envoy proxy handles the TLS handshake with the destination, wraps the plain text request in an encrypted mTLS tunnel, and sends it over the wire.</li></ul><h3>2. In Transit</h3><ul><li>Anyone sniffing the network traffic between the Kubernetes nodes or pods will only see encrypted garbage. The headers, URIs, and payloads are completely unreadable.</li></ul><h3>3. Ingress &amp; Auto-Decryption (Arriving at the Destination)</h3><ul><li>The encrypted traffic arrives at <strong>Pod B</strong>, but it doesn’t hit your application first.</li><li>It is intercepted by <strong>Pod B’s Envoy proxy sidecar</strong>.</li><li>This proxy validates Pod A’s cryptographic certificate (ensuring authentication) and <strong>automatically decrypts the payload</strong>.</li><li>The proxy then forwards the raw, plain HTTP request over the local loopback interface (localhost) directly to <strong>Application B</strong>.</li></ul><p><strong>Hands on POC — </strong><a href="https://medium.com/@suneelr.kandali/securing-microservices-with-istio-service-mesh-theory-and-hands-on-poc-part-2-d671f8f5a8b7">https://medium.com/@suneelr.kandali/securing-microservices-with-istio-service-mesh-theory-and-hands-on-poc-part-2-d671f8f5a8b7</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3e78556dc5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Polyglot Distributed Tracing Playground with OpenTelemetry, Grafana, and Tempo]]></title>
            <link>https://medium.com/@suneelr.kandali/building-a-polyglot-distributed-tracing-playground-with-opentelemetry-grafana-and-tempo-22854037ae1a?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/22854037ae1a</guid>
            <category><![CDATA[tempo]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 02:56:21 GMT</pubDate>
            <atom:updated>2026-06-21T03:07:19.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Whqi2jr-Jm_W3BLSXjIjg.jpeg" /></figure><p>In a modern cloud-native ecosystem, a single user request can traverse an intricate web of microservices, each built on different runtime engines. When a failure or latency spike occurs, finding the root cause across a polyglot infrastructure can feel like searching for a needle in a haystack.</p><p>This is where <strong>Distributed Tracing</strong> becomes critical. By passing a unique trace context across network boundaries, we can visualize the entire journey of a request.</p><p>In this hands-on guide, we will build a multi-layered distributed tracing playground featuring three different technology stacks:</p><ol><li><strong>API Gateway:</strong> Python (FastAPI)</li><li><strong>Processing Layer:</strong> Java (Spring Boot 3.x)</li><li><strong>Downstream Service:</strong> Node.js (Express)</li></ol><p>We will instrument all three services using <strong>OpenTelemetry (OTel)</strong> and send the telemetry data to <strong>Grafana Tempo</strong> for end-to-end visualization.</p><h3>Architecture Overview</h3><p>Before diving into the code, let’s look at how data and trace contexts flow through our sandbox:</p><p>Plaintext</p><pre>[ Client Request ] <br>       │<br>       ▼<br>┌──────────────────────┐<br>│   gateway-fastapi    │  (Instruments via OTel Python SDK -&gt; gRPC)<br>└──────────┬───────────┘<br>           │  [HTTP Call + W3C Trace Context Headers]<br>           ▼<br>┌──────────────────────┐<br>│ processor-springboot │  (Instruments via Micrometer Tracing -&gt; gRPC)<br>└──────────┬───────────┘<br>           │  [HTTP Call + W3C Trace Context Headers]<br>           ▼<br>┌──────────────────────┐<br>│   downstream-node    │  (Instruments via OTel Node.js SDK -&gt; HTTP)<br>└──────────────────────┘<br>       │              │<br>       │ (OTLP Traces)│ (OTLP Traces)<br>       ▼              ▼<br>┌────────────────────────────────────────────────────────┐<br>│                     Grafana Tempo                      │<br>└────────────────────────────────────────────────────────┘</pre><p>Every service automatically intercepts incoming headers, extracts the execution context, appends its own “span” (unit of work), and propagates the updated context down the line.</p><h3>Project Structure</h3><p>Here is the blueprint of the project workspace we are going to build:</p><p>Plaintext</p><pre>distributed-tracing-playground/<br>├── docker-compose.yml<br>├── config/<br>│   ├── tempo.yaml<br>│   └── grafana-datasources.yaml<br>├── gateway-fastapi/<br>│   ├── main.py<br>│   ├── requirements.txt<br>│   └── Dockerfile<br>├── processor-springboot/<br>│   ├── src/main/java/com/example/processor/ProcessorApplication.java<br>│   ├── pom.xml<br>│   └── Dockerfile<br>└── downstream-node/<br>    ├── server.js<br>    ├── package.json<br>    └── Dockerfile</pre><h3>1. Setting Up the Infrastructure</h3><p>To handle our storage and visualization backend, we configure Grafana and Tempo to spin up via Docker Compose.</p><h3>Tempo Configuration (config/tempo.yaml)</h3><p>Tempo needs a basic structural configuration file to define its operational ports and local storage retention properties.</p><p>YAML</p><pre>stream_over_http: true<br>server:<br>  http_listen_port: 3200<br>distributor:<br>  receivers:<br>    otlp:<br>      protocols:<br>        http:<br>        grpc:<br>ingester:<br>  max_block_duration: 5m<br>compactor:<br>  compaction:<br>    block_retention: 1h<br>storage:<br>  trace:<br>    backend: local<br>    local:<br>      path: /tmp/tempo/traces</pre><h3>Automating Grafana Provisioning (config/grafana-datasources.yaml)</h3><p>To avoid manual configuration upon booting the UI dashboard, we can pre-load Tempo as our default tracing datasource.</p><p>YAML</p><pre>apiVersion: 1<br>datasources:<br>  - name: Tempo<br>    type: tempo<br>    access: proxy<br>    url: http://tempo:3200<br>    uid: tempo<br>    isDefault: true<br>    jsonData:<br>      httpMethod: GET</pre><h3>2. Writing the Polyglot Services</h3><h3>Layer 1: Python FastAPI Gateway</h3><p>Using the OpenTelemetry SDK for Python, we auto-instrument FastAPI to trace incoming HTTP traffic and the httpx client to inject headers into outgoing requests over gRPC port 4317.</p><p>gateway-fastapi/main.py:</p><p>Python</p><pre>import os<br>import httpx<br>from fastapi import FastAPI<br>from opentelemetry import trace<br>from opentelemetry.sdk.trace import TracerProvider<br>from opentelemetry.sdk.trace.export import BatchSpanProcessor<br>from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter<br>from opentelemetry.sdk.resources import Resource<br>from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor<br>from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor<br><br># Initialize OTel SDK<br>resource = Resource.create(attributes={&quot;service.name&quot;: os.getenv(&quot;OTEL_SERVICE_NAME&quot;, &quot;gateway-fastapi&quot;)})<br>provider = TracerProvider(resource=resource)<br>processor = BatchSpanProcessor(OTLPSpanExporter(endpoint=os.getenv(&quot;OTEL_EXPORTER_OTLP_ENDPOINT&quot;, &quot;http://tempo:4317&quot;), insecure=True))<br>provider.add_span_processor(processor)<br>trace.set_tracer_provider(provider)<br>app = FastAPI()<br># Auto-instrument framework hooks<br>FastAPIInstrumentor.instrument_app(app)<br>HTTPXClientInstrumentor.instrument()<br>SPRINGBOOT_URL = os.getenv(&quot;SPRINGBOOT_SERVICE_URL&quot;, &quot;http://localhost:8080&quot;)<br>@app.get(&quot;/api/start&quot;)<br>async def start_journey():<br>    async with httpx.AsyncClient() as client:<br>        response = await client.get(f&quot;{SPRINGBOOT_URL}/process&quot;)<br>        return {&quot;gateway&quot;: &quot;FastAPI received request&quot;, &quot;downstream&quot;: response.json()}</pre><h3>Layer 2: Spring Boot 3.x Processing Service</h3><p>Spring Boot 3 seamlessly builds upon Micrometer Tracing. By configuring a Micrometer-to-OpenTelemetry bridge dependency, we can extract parent traces from FastAPI and stream telemetry onward to Tempo.</p><p>processor-springboot/src/main/java/com/example/processor/ProcessorApplication.java:</p><p>Java</p><pre>package com.example.processor;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RestController;<br>import org.springframework.web.client.RestTemplate;<br>import org.springframework.beans.factory.annotation.Value;<br>@SpringBootApplication<br>public class ProcessorApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(ProcessorApplication.class, args);<br>    }<br>    @Bean<br>    public RestTemplate restTemplate() {<br>        return new RestTemplate(); // Automatically instrumented by Spring Boot Bootstrapping<br>    }<br>}<br>@RestController<br>class ProcessController {<br>    private final RestTemplate restTemplate;<br>    <br>    @Value(&quot;${NODE_SERVICE_URL:http://localhost:8081}&quot;)<br>    private String nodeServiceUrl;<br>    public ProcessController(RestTemplate restTemplate) {<br>        this.restTemplate = restTemplate;<br>    }<br>    @GetMapping(&quot;/process&quot;)<br>    public java.util.Map&lt;String, Object&gt; process() {<br>        var response = restTemplate.getForObject(nodeServiceUrl + &quot;/finalize&quot;, java.util.Map.class);<br>        return java.util.Map.of(<br>            &quot;springboot&quot;, &quot;Spring Boot processed middle layer&quot;,<br>            &quot;downstream&quot;, response<br>        );<br>    }<br>}</pre><h3>Layer 3: Node.js Downstream Service</h3><p>The final layer utilizes the standard Node.js OpenTelemetry instrumentation modules, executing a short delay to simulate network/database latency before closing the span chain over HTTP port 4318.</p><p>downstream-node/server.js:</p><p>JavaScript</p><pre>const { NodeTracerProvider } = require(&#39;@opentelemetry/sdk-trace-node&#39;);<br>const { SimpleSpanProcessor } = require(&#39;@opentelemetry/sdk-trace-base&#39;);<br>const { OTLPTraceExporter } = require(&#39;@opentelemetry/exporter-trace-otlp-http&#39;);<br>const { registerInstrumentations } = require(&#39;@opentelemetry/instrumentation&#39;);<br>const { HttpInstrumentation } = require(&#39;@opentelemetry/instrumentation-http&#39;);<br>const { ExpressInstrumentation } = require(&#39;@opentelemetry/instrumentation-express&#39;);<br>const { Resource } = require(&#39;@opentelemetry/resources&#39;);<br>const { SemanticResourceAttributes } = require(&#39;@opentelemetry/semantic-conventions&#39;);<br><br>const provider = new NodeTracerProvider({<br>  resource: new Resource({<br>    [SemanticResourceAttributes.SERVICE_NAME]: &#39;downstream-node&#39;,<br>  }),<br>});<br>const exporter = new OTLPTraceExporter({ url: &#39;http://tempo:4318/v1/traces&#39; });<br>provider.addSpanProcessor(new SimpleSpanProcessor(exporter));<br>provider.register();<br>registerInstrumentations({<br>  instrumentations: [new HttpInstrumentation(), new ExpressInstrumentation()],<br>});<br>const express = require(&#39;express&#39;);<br>const app = express();<br>app.get(&#39;/finalize&#39;, (req, res) =&gt; {<br>  setTimeout(() =&gt; {<br>    res.json({ node: &quot;Node.js finished execution chain successfully.&quot; });<br>  }, 80);<br>});<br>app.listen(8081);</pre><h3>3. Orchestrating with Docker Compose</h3><p>To bind these layers together, here is our full docker-compose.yml file mapping ports, establishing service dependencies, and overriding environment variables.</p><p>YAML</p><pre>version: &#39;3.8&#39;<br>networks:<br>  tracing-net:<br>    driver: bridge<br>services:<br>  tempo:<br>    image: grafana/tempo:latest<br>    command: [ &quot;-config.file=/etc/tempo.yaml&quot; ]<br>    volumes:<br>      - ./config/tempo.yaml:/etc/tempo.yaml<br>    ports:<br>      - &quot;3200:3200&quot;<br>      - &quot;4317:4317&quot;<br>      - &quot;4318:4318&quot;<br>    networks:<br>      - tracing-net<br>  grafana:<br>    image: grafana/grafana:latest<br>    volumes:<br>      - ./config/grafana-datasources.yaml:/etc/grafana/provisioning/datasources/datasources.yaml<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - tempo<br>    networks:<br>      - tracing-net<br>  gateway-fastapi:<br>    build: ./gateway-fastapi<br>    ports:<br>      - &quot;8000:8000&quot;<br>    environment:<br>      - SPRINGBOOT_SERVICE_URL=http://processor-springboot:8080<br>      - OTEL_EXPORTER_OTLP_ENDPOINT=http://tempo:4317<br>    depends_on:<br>      - tempo<br>    networks:<br>      - tracing-net<br>  processor-springboot:<br>    build: ./processor-springboot<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      - NODE_SERVICE_URL=http://downstream-node:8081<br>    depends_on:<br>      - tempo<br>    networks:<br>      - tracing-net<br>  downstream-node:<br>    build: ./downstream-node<br>    ports:<br>      - &quot;8081:8081&quot;<br>    depends_on:<br>      - tempo<br>    networks:<br>      - tracing-net</pre><h3>4. Running and Testing the Playground</h3><h3>Booting Up</h3><p>Execute the build sequence from your terminal at the repository root:</p><p>Bash</p><pre>docker-compose up --build -d</pre><h3>Triggering a Multi-Layer Trace</h3><p>Fire a request at the API Gateway using curl or your browser:</p><p>Bash</p><pre>curl http://localhost:8000/api/start</pre><p>You should receive a combined JSON payload confirming all three service hops executed perfectly:</p><p>JSON</p><pre>{<br>  &quot;gateway&quot;: &quot;FastAPI received request&quot;,<br>  &quot;downstream&quot;: {<br>    &quot;springboot&quot;: &quot;Spring Boot processed middle layer&quot;,<br>    &quot;downstream&quot;: {<br>      &quot;node&quot;: &quot;Node.js finished execution chain successfully.&quot;<br>    }<br>  }<br>}</pre><h3>Visualizing the Trace in Grafana</h3><ul><li>Open your browser and navigate to <strong>http://localhost:3000</strong> (Login using admin / admin).</li><li>Click on the <strong>Explore</strong> compass icon in the left menu.</li><li>Switch the active datasource dropdown at the top to <strong>Tempo</strong>.</li><li>Inside the panel query options, choose the <strong>Search</strong> sub-tab.</li><li>Select gateway-fastapi from the <strong>Service Name</strong> filter dropdown and click <strong>Run Query</strong>.</li></ul><p>Click on the generated trace ID. You will see a beautiful, nested waterfall diagram visualizing exactly how long each application service took to execute, confirming context propagation worked successfully across Python, Java, and Node.js.</p><h3>Tearing Down Resources</h3><p>Once your experiments are complete, wipe the container stacks and local networks easily:</p><p>Bash</p><pre>docker-compose down -v</pre><h3>Conclusion</h3><p>By adopting OpenTelemetry standards, decoupled microservices from strict vendor-specific codebases. Whether writing code in Python, Java, or JavaScript, the underlying spans communicate seamlessly using open standards.</p><p>This playground can serve as a template for adding more layers, simulating error states, or testing out advanced dashboards inside Grafana.</p><p>Happy tracing! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22854037ae1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL Federation on GKE — A Hands-On Learning Guide]]></title>
            <link>https://medium.com/@suneelr.kandali/graphql-federation-on-gke-a-hands-on-learning-guide-ab2fde80b440?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab2fde80b440</guid>
            <category><![CDATA[federated-graph]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[subgraph]]></category>
            <category><![CDATA[gke]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 19:24:07 GMT</pubDate>
            <atom:updated>2026-06-21T01:53:28.576Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>💻 </em><strong><em>Important Note for Readers:</em></strong><em> The terminal commands, setup steps, and package managers (such as Homebrew) used throughout this tutorial are explicitly tailored for macOS. If you are running Windows or Linux, you will need to adjust your local environment setup and CLI installations accordingly.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UU8rZ8qMFMfIl5rx-28iFA.png" /></figure><p>A complete guide to building and deploying an <strong>Apollo Federation v2</strong> GraphQL API on Google Kubernetes Engine (GKE), where two independent subgraphs — <strong>Products</strong> and <strong>Reviews</strong> — are composed into a single unified graph through an <strong>Apollo Router</strong>.</p><h3>What you will do</h3><ol><li>Install local tools</li><li>Understand how GraphQL Federation splits a schema across multiple services.</li><li>Setup Apollo Studio for Federated graph</li><li>Authenticate Google Cloud</li><li>Create new project in Google cloud</li><li>Create a GKE cluster and connect kubectl.</li><li>Build and push Docker images for each subgraph to Google Container Registry (GCR).</li><li>Deploy the Products subgraph, Reviews subgraph, and Apollo Router to GKE.</li><li>Verify the federated GraphQL API with cURL and Apollo Sandbox.</li><li>Troubleshoot common issues.</li><li>Clean up resources when finished.</li></ol><h3>1. Prerequisites</h3><p>You need the following installed on your computer:</p><ul><li>gcloud</li><li>kubectl</li><li>docker with <a href="https://docs.docker.com/buildx/working-with-buildx/">Buildx</a></li><li>rover</li><li>A GCP project with billing enabled</li></ul><p>If you do not already have the required tools installed, follow these steps.</p><h3>Verify installed tools</h3><p>Check that the required commands are already available before installing:</p><pre>docker version<br>kubectl version --client<br>gcloud version<br>rover --version</pre><p>If any command fails, install the missing tool using the instructions below.</p><h3>Install Docker</h3><p>Download Docker Desktop for your platform from: <a href="https://www.docker.com/get-started">https://www.docker.com/get-started</a></p><p>After installation, verify Docker is running:</p><pre>docker version</pre><h3>Install kubectl</h3><p>Follow the instructions at: <a href="https://kubernetes.io/docs/tasks/tools/">https://kubernetes.io/docs/tasks/tools/</a></p><p>For macOS with Homebrew:</p><pre>brew install kubectl</pre><p>Verify installation:</p><pre>kubectl version --client</pre><h3>Install Google Cloud SDK</h3><ol><li>Download and install the SDK for your platform from: <a href="https://cloud.google.com/sdk/docs/install">https://cloud.google.com/sdk/docs/install</a></li><li>Confirm the SDK is installed and working:</li></ol><pre>gcloud version</pre><h3>3.2 Install Rover CLI</h3><p>Rover is the Apollo command-line tool for working with your graph. Install it for your platform:</p><pre>brew install apollographql/rover/rover</pre><h4>Verify Installation</h4><pre>rover --version</pre><p>Expected output:</p><pre>rover 0.2x.x (some hash)</pre><h3>Authenticate with Google Cloud</h3><ol><li>Initialize the SDK and log in to your Google account:</li></ol><pre>gcloud init</pre><ol><li>Authenticate with your Google account:</li></ol><pre>gcloud auth login</pre><ol><li>Verify the active account and current configuration:</li></ol><pre>gcloud auth list</pre><pre>gcloud config list</pre><h3>Create a Google Cloud project</h3><p>If you do not already have a project, create one now:</p><pre>gcloud projects create federated-graph-demo --name=&quot;Federated Graph Demo&quot;</pre><p>Enable billing and link it to your project using the Cloud Console (<a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a>) if needed.</p><p>Set the active project:</p><pre>gcloud config set project federated-graph-demo</pre><h3>Enable required APIs</h3><pre>gcloud services enable container.googleapis.com</pre><h3>Clone the repository</h3><p>Clone the project repository from GitHub and navigate to the project folder:</p><pre>git clone https://github.com/suneelkandali/gcp-gke-federated-graph-demo.git</pre><pre>cd gcp-gke-federated-graph-demo</pre><p>All subsequent commands in this tutorial should be executed from within the gcp-gke-federated-graph-demo directory.</p><h3>2. Understand the Architecture</h3><p>This project demonstrates <strong>Apollo Federation v2</strong>, a pattern for building a single GraphQL API from multiple independent services (called <strong>subgraphs</strong>). An <strong>Apollo Router</strong> sits in front of the subgraphs and composes their schemas into a single unified endpoint.</p><h3>How Federation Works</h3><ul><li>The <strong>Products subgraph</strong> owns the Product type and defines base fields (id, name, price).</li><li>The <strong>Reviews subgraph</strong> extends the Product type by adding a reviews field, using the @key and @external directives to reference the Product entity.</li><li>The <strong>Apollo Router</strong> queries both subgraphs and merges the results into a single response.</li></ul><h3>Architecture Diagram</h3><pre>                    ┌──────────────┐<br>                    │    Router    │<br>                    │   (Port 4000)│<br>                    └──────┬───────┘<br>                           │<br>              ┌────────────┴────────────┐<br>              │                         │<br>     ┌────────▼────────┐      ┌─────────▼────────┐<br>     │  Products API   │      │   Reviews API    │<br>     │  (Port 4001)    │      │   (Port 4002)    │<br>     └─────────────────┘      └──────────────────┘</pre><h3>Project Structure</h3><pre>gcp-gke-federated-graph-demo/<br>├── subgraphs/<br>│   ├── products/<br>│   │   ├── Dockerfile<br>│   │   ├── package.json<br>│   │   ├── index.js<br>│   │   └── schema.graphql<br>│   └── reviews/<br>│       ├── Dockerfile<br>│       ├── package.json<br>│       ├── index.js<br>│       └── schema.graphql<br>├── k8s/<br>│   ├── products-deployment.yaml<br>│   ├── reviews-deployment.yaml<br>│   └── router-deployment.yaml<br>└── README.md</pre><h3>Products Subgraph Schema</h3><pre>extend schema @link(url: &quot;https://specs.apollo.dev/federation/v2.7&quot;, import: [&quot;@key&quot;])</pre><pre>type Product @key(fields: &quot;id&quot;) {<br>  id: ID!<br>  name: String!<br>  price: Float!<br>}</pre><pre>type Query {<br>  products: [Product!]!<br>  product(id: ID!): Product<br>}</pre><h3>Reviews Subgraph Schema</h3><pre>extend schema @link(url: &quot;https://specs.apollo.dev/federation/v2.7&quot;, import: [&quot;@key&quot;, &quot;@external&quot;])</pre><pre>type Review {<br>  id: ID!<br>  rating: Int!<br>  comment: String!<br>}</pre><pre>extend type Product @key(fields: &quot;id&quot;) {<br>  id: ID! @external<br>  reviews: [Review!]!<br>}</pre><h3>3. Setup Apollo Studio for Federated graph</h3><p><a href="https://studio.apollographql.com/">Apollo Studio</a> is a cloud-based GraphQL platform that provides schema registry, performance metrics, operation tracking, and schema change validation for your federated graph. <a href="https://www.apollographql.com/docs/rover/">Rover</a> is the official Apollo CLI used to publish and check your subgraph schemas against Apollo Studio.</p><h3>3.1 Create an Apollo Studio Graph</h3><ol><li>Go to <a href="https://studio.apollographql.com/">https://studio.apollographql.com</a> and sign up or log in.</li><li>Click <strong>New Graph</strong> (or <strong>Create a New Graph</strong>).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5MGQeqKBcBemueiQVVRgg.png" /></figure><p>3. Choose <strong>Federated</strong> as the graph type.</p><p>4. Give your graph a name (e.g., My-Graph) and select a <strong>Deployment Region</strong> close to your users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*cyuTRNa-zzfeejXl-eyXmw.png" /></figure><p>5. Apollo Studio will generate a <strong>Graph API Key</strong> for you. Copy it — you will need it shortly.</p><p>6. Note your <strong>Graph Reference</strong> (also called graph ref), which has the format Your-Graph-Name@current (e.g., My-Graph-9f5n9i@current).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*nOm-uq_QVFJJbZFDVmh_vQ.png" /></figure><blockquote><strong><em>Important:</em></strong><em> Keep your API key safe. It grants access to publish schemas and view metrics for your graph. Do not commit it to source control.</em></blockquote><h3>3.3 Authenticate Rover</h3><p>Set your Apollo API key as an environment variable. Replace service:YOUR_GRAPH_ID:YOUR_KEY with the key you copied from Apollo Studio:</p><pre>export APOLLO_KEY=service:YOUR_GRAPH_ID:YOUR_KEY</pre><pre>Example - export APOLLO_KEY=service:federated-graph-demo-suneelkandali:xxxxxxxxxxxxxxxx</pre><p>Set your graph reference:</p><pre>export APOLLO_GRAPH_REF=YOUR_GRAPH_ID@current</pre><pre>Example - export APOLLO_GRAPH_REF=federated-graph-demo-suneelkandali@current</pre><blockquote><strong><em>Tip:</em></strong><em> Add these </em><em>export lines to your </em><em>~/.zshrc so they persist across terminal sessions. Alternatively, use a </em><em>.env file and source it before running Rover commands.</em></blockquote><p>Verify Rover can connect to Apollo Studio:</p><pre>rover config whoami</pre><p>Expected output (Similar):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*ZEijDAVorX201RpSJLa3-w.png" /></figure><h3>4. Create the GKE cluster</h3><p>Run these commands in your terminal:</p><pre>gcloud container clusters create federation-demo-cluster \<br>  --zone us-central1-a \<br>  --num-nodes=2 \<br>  --machine-type=e2-standard-2 \<br>  --release-channel=regular</pre><p>Then connect kubectl to the cluster:</p><pre># Install GKE auth plugin<br>gcloud components install gke-gcloud-auth-plugin</pre><pre># Get cluster credentials<br>gcloud container clusters get-credentials federation-demo-cluster \<br>  --zone us-central1-a</pre><pre># Verify connection<br>kubectl config current-context</pre><h3>5. Build &amp; Push Docker Images</h3><blockquote><strong><em>Important:</em></strong><em> When building on macOS (Apple Silicon/ARM), you </em><strong><em>must</em></strong><em> specify </em><em>--platform linux/amd64 because GKE nodes run on AMD64 architecture. Building without this flag will result in </em><em>ImagePullBackOff errors.</em></blockquote><h3>Configure Docker for GCR</h3><pre>gcloud auth configure-docker --quiet</pre><h3>Build Products Subgraph</h3><pre>cd subgraphs/products</pre><pre>docker buildx build --no-cache \<br>    --platform linux/amd64 \<br>    --provenance=false --sbom=false \<br>    -t gcr.io/YOUR_PROJECT_ID/subgraph-products:1.0.3 \<br>    --push .</pre><h3>Build Reviews Subgraph</h3><pre>cd subgraphs/reviews</pre><pre>docker buildx build --no-cache \<br>    --platform linux/amd64 \<br>    --provenance=false --sbom=false \<br>    -t gcr.io/YOUR_PROJECT_ID/subgraph-reviews:1.0.3 \<br>    --push .</pre><p>Replace YOUR_PROJECT_ID with your actual GCP project ID. You can retrieve it with:</p><pre>gcloud config get-value project</pre><h3>6. Deploy to Kubernetes</h3><h3>Deploy Subgraphs</h3><p>Deploy the Products and Reviews subgraphs first:</p><pre># Deploy products subgraph<br>kubectl apply -f k8s/products-deployment.yaml</pre><pre># Deploy reviews subgraph<br>kubectl apply -f k8s/reviews-deployment.yaml</pre><p>Wait for the subgraph pods to be running before proceeding:</p><pre>kubectl get pods</pre><p>Once the subgraphs are healthy, publish their schemas to Apollo Studio using Rover (see <a href="https://alanhe421.github.io/markdown-to-medium-tool/#71-publish-subgraph-schemas">Step 7 Publish Subgraph Schemas</a>).</p><h3>Deploy Apollo Router</h3><p>After publishing the subgraph schemas, deploy the Apollo Router:</p><pre># Deploy router<br>kubectl apply -f k8s/router-deployment.yaml</pre><h3>Get the Router External IP</h3><p>The Apollo Router is exposed via a LoadBalancer service. Retrieve its external IP:</p><pre>kubectl get service router-service</pre><p>Expected output:</p><pre>NAME            TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)        AGE<br>router-service  LoadBalancer   10.x.x.x       34.67.230.190   80:3xxxx/TCP   5m</pre><blockquote><strong><em>Note:</em></strong><em> It may take 1–2 minutes for the external IP to be provisioned. Wait until the </em><em>EXTERNAL-IP column shows an IP address instead of </em><em>&lt;pending&gt;.</em></blockquote><p>You can watch for the IP to appear:</p><pre>kubectl get service router-service --watch</pre><h3>Verify Deployment</h3><pre># Check pods are running<br>kubectl get pods</pre><pre># Expected output:<br># NAME                                   READY   STATUS    RESTARTS   AGE<br># products-deployment-xxx-yyy            1/1     Running   0          30s<br># products-deployment-xxx-zzz            1/1     Running   0          30s<br># reviews-deployment-xxx-yyy             1/1     Running   0          30s<br># reviews-deployment-xxx-zzz             1/1     Running   0          30s</pre><pre># Check deployments<br>kubectl get deployments</pre><pre># Check services<br>kubectl get services</pre><h3>7. Publish Subgraph Schemas &amp; Connect Apollo Studio</h3><h3>7.1 Publish Subgraph Schemas</h3><p>The --routing-url should point to the Kubernetes <strong>service DNS name</strong> (not the external IP), since Rover runs from within or near the cluster network.</p><h4>Publish the Products Subgraph</h4><pre>rover subgraph publish $APOLLO_GRAPH_REF \<br>    --name products \<br>    --schema ./subgraphs/products/schema.graphql \<br>    --routing-url http://products-service:4001/</pre><p>Expected output:</p><pre>🚀 Subgraph schemas published to &#39;My-Graph-9f5n9i@current&#39;<br>  → Products subgraph: publish succeeded<br>  → No new schema changes detected (already up to date)</pre><h4>Publish the Reviews Subgraph</h4><pre>rover subgraph publish $APOLLO_GRAPH_REF \<br>    --name reviews \<br>    --schema ./subgraphs/reviews/schema.graphql \<br>    --routing-url http://reviews-service:4002/</pre><p>After publishing both subgraphs, Apollo Studio will compose a supergraph schema and make it available to your Apollo Router.</p><h3>7.2 Check Schema Changes (Optional but Recommended)</h3><p>Before publishing, you can validate that your schema changes are compatible with the rest of the graph:</p><pre>rover subgraph check $APOLLO_GRAPH_REF \<br>    --name products \<br>    --schema ./subgraphs/products/schema.graphql</pre><p>This runs composition checks against the existing subgraphs in Apollo Studio and reports any breaking changes or composition errors.</p><h3>7.3 View Your Graph in Apollo Studio</h3><p>After publishing your subgraphs:</p><ol><li>Go to <a href="https://studio.apollographql.com/">https://studio.apollographql.com</a>.</li><li>Select your graph from the dashboard.</li><li>You will see:</li></ol><ul><li><strong>Schema</strong> — The composed supergraph schema from both subgraphs.</li><li><strong>Explorer</strong> — A query builder for testing operations against your graph.</li><li><strong>Metrics</strong> — Performance data (once the router sends usage reports).</li><li><strong>Checks</strong> — History of schema change validations.</li></ul><h3>7.4 Connect the Apollo Router to Apollo Studio</h3><p>The Apollo Router is configured to report metrics to Apollo Studio via the environment variables in k8s/router-deployment.yaml:</p><pre>env:<br>- name: APOLLO_KEY<br>  value: &quot;service:YOUR_GRAPH_ID:YOUR_KEY&quot;<br>- name: APOLLO_GRAPH_REF<br>  value: &quot;YOUR_GRAPH_ID@current&quot;</pre><p>Replace the placeholder values with your actual Apollo key and graph ref before deploying the router.</p><p>Once deployed, the router will:</p><ul><li><strong>Fetch the composed supergraph schema</strong> from Apollo Studio at startup.</li><li><strong>Report operation metrics</strong> (latency, error rates, field usage) to Apollo Studio.</li><li><strong>Receive schema updates</strong> automatically when you publish new subgraph schemas via Rover.</li></ul><h3>7.5 Useful Rover Commands</h3><pre># List all subgraphs in your graph<br>rover subgraph list $APOLLO_GRAPH_REF</pre><pre># Get the composed supergraph schema<br>rover supergraph fetch $APOLLO_GRAPH_REF</pre><pre># Get a subgraph&#39;s schema<br>rover subgraph fetch $APOLLO_GRAPH_REF --name products</pre><pre># Check rover configuration<br>rover config list</pre><h3>7.6 Quick Reference — Rover + Apollo Studio</h3><ul><li><strong>Install Rover (macOS/Linux):</strong> curl -sSL https://rover.apollo.dev/nix/latest | sh</li><li><strong>Install Rover (macOS Homebrew):</strong> brew install apollographql/rover/rover</li><li><strong>Verify identity:</strong> rover config whoami</li><li><strong>Publish a subgraph:</strong> rover subgraph publish $APOLLO_GRAPH_REF --name NAME --schema PATH --routing-url URL</li><li><strong>Check schema changes:</strong> rover subgraph check $APOLLO_GRAPH_REF --name NAME --schema PATH</li><li><strong>List subgraphs:</strong> rover subgraph list $APOLLO_GRAPH_REF</li><li><strong>View graph in browser:</strong> Open <a href="https://studio.apollographql.com/">studio.apollographql.com</a></li></ul><h3>8. Validate the deployment</h3><p>After the workflow completes, confirm the federated GraphQL API is working correctly.</p><h3>8.1 Check pods and services</h3><p>Verify that all deployments are running and services are available:</p><pre>kubectl get pods<br>kubectl get services</pre><p>All pods should show STATUS = Running and the router-service should have an external IP.</p><h3>8.2 Test with cURL</h3><h4>Query All Products with Reviews (Federated Query)</h4><p>This query demonstrates Apollo Federation by fetching Product fields from the <strong>Products</strong> subgraph and Review fields from the <strong>Reviews</strong> subgraph in a single request:</p><pre>curl -X POST \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;query&quot;: &quot;query GetFederatedProducts { products { id name price reviews { id rating comment } } }&quot;}&#39; \<br>  http://EXTERNAL_IP</pre><p>Replace EXTERNAL_IP with your router&#39;s external IP (e.g., 34.67.230.190):</p><pre>curl -X POST \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;query&quot;: &quot;query GetFederatedProducts { products { id name price reviews { id rating comment } } }&quot;}&#39; \<br>  http://34.67.230.190</pre><p><strong>Expected Response:</strong></p><pre>{<br>  &quot;data&quot;: {<br>    &quot;products&quot;: [<br>      {<br>        &quot;id&quot;: &quot;1&quot;,<br>        &quot;name&quot;: &quot;Enterprise Database Tool&quot;,<br>        &quot;price&quot;: 299.99,<br>        &quot;reviews&quot;: [<br>          {<br>            &quot;id&quot;: &quot;101&quot;,<br>            &quot;rating&quot;: 5,<br>            &quot;comment&quot;: &quot;Essential tool for system metrics!&quot;<br>          },<br>          {<br>            &quot;id&quot;: &quot;102&quot;,<br>            &quot;rating&quot;: 4,<br>            &quot;comment&quot;: &quot;Great UI, needs minor bug fixes.&quot;<br>          }<br>        ]<br>      },<br>      {<br>        &quot;id&quot;: &quot;2&quot;,<br>        &quot;name&quot;: &quot;Cloud Log Aggregator Plugin&quot;,<br>        &quot;price&quot;: 49.99,<br>        &quot;reviews&quot;: [<br>          {<br>            &quot;id&quot;: &quot;103&quot;,<br>            &quot;rating&quot;: 5,<br>            &quot;comment&quot;: &quot;Flawless integration with Splunk/Docker.&quot;<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><h4>Query a Single Product by ID</h4><pre>curl -X POST \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;query&quot;: &quot;query GetProduct { product(id: \&quot;1\&quot;) { id name price reviews { id rating comment } } }&quot;}&#39; \<br>  http://EXTERNAL_IP</pre><h4>Query Only Products (No Reviews)</h4><pre>curl -X POST \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;query&quot;: &quot;query GetProductsOnly { products { id name price } }&quot;}&#39; \<br>  http://EXTERNAL_IP</pre><h4>Using a Variable Query</h4><pre>curl -X POST \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;query&quot;: &quot;query GetProduct($id: ID!) { product(id: $id) { id name price reviews { rating comment } } }&quot;, &quot;variables&quot;: {&quot;id&quot;: &quot;1&quot;}}&#39; \<br>  http://EXTERNAL_IP</pre><h4>Introspection Query (Verify Schema)</h4><pre>curl -X POST \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;query&quot;: &quot;{ __schema { queryType { name } types { name kind } } }&quot;}&#39; \<br>  http://EXTERNAL_IP</pre><blockquote><strong><em>Tip:</em></strong><em> You can pipe the response through </em><em>jq for formatted output:</em></blockquote><blockquote><em>curl -s -X POST \ -H &quot;Content-Type: application/json&quot; \ --data &#39;{&quot;query&quot;: &quot;query GetFederatedProducts { products { id name price reviews { id rating comment } } }&quot;}&#39; \ http://EXTERNAL_IP | jq .</em></blockquote><h3>8.3 Test with Apollo Sandbox</h3><p><a href="https://studio.apollographql.com/sandbox">Apollo Sandbox</a> is a free, browser-based GraphQL IDE that provides auto-completion, schema documentation, and a query builder — making it ideal for exploring your federated graph.</p><h4>Step 1: Open Apollo Sandbox</h4><p>Open your browser and navigate to:</p><pre>https://studio.apollographql.com/sandbox</pre><blockquote><strong><em>Screenshot:</em></strong><em> Opening Apollo Sandbox in the browser</em></blockquote><h4>Step 2: Connect to Your Router Endpoint</h4><ol><li>In the <strong>URL bar</strong> at the top of Apollo Sandbox, enter your router’s endpoint URL:</li></ol><ul><li><a href="http://external_ip/">http://EXTERNAL_IP</a></li></ul><ol><li>For example: <a href="http://34.67.230.190/">http://34.67.230.190</a></li><li>Press <strong>Enter</strong> or click the <strong>Connect</strong> button.</li></ol><blockquote><strong><em>Note:</em></strong><em> Since the router is exposed over HTTP (not HTTPS), you may need to confirm a browser warning about loading an insecure page. Click </em><strong><em>Continue</em></strong><em> or </em><strong><em>Proceed</em></strong><em> to accept.</em></blockquote><blockquote><strong><em>Screenshot:</em></strong><em> Entering the router endpoint URL</em></blockquote><h4>Step 3: Explore the Schema</h4><p>Once connected, Apollo Sandbox automatically fetches and displays your federated schema:</p><ol><li>Click the <strong>Schema</strong> tab (📚 icon) in the left sidebar.</li><li>You’ll see the combined schema from both the <strong>Products</strong> and <strong>Reviews</strong> subgraphs:</li></ol><ul><li>Product type with fields: id, name, price, reviews</li><li>Review type with fields: id, rating, comment</li><li>Query type with: products, product(id: ID!)</li></ul><blockquote><strong><em>Screenshot:</em></strong><em> Viewing the federated schema in Apollo Sandbox</em></blockquote><h4>Step 4: Write and Execute a Query</h4><ol><li>Click the <strong>Operations</strong> tab (📝 icon) in the left sidebar.</li><li>Type your federated query in the query editor (left pane):</li></ol><pre>query GetFederatedProducts {<br>  products {<br>    id<br>    name<br>    price<br>    reviews {<br>      id<br>      rating<br>      comment<br>    }<br>  }<br>}</pre><ol><li>Click the <strong>Run</strong> button (▶️) or press Cmd+Enter.</li><li>The response appears in the right pane, showing data from both subgraphs merged into a single response.</li></ol><blockquote><strong><em>Screenshot:</em></strong><em> Writing and running a federated query</em></blockquote><h4>Step 5: Test a Single Product Query</h4><p>Try a different query to fetch a single product by ID:</p><pre>query GetProduct {<br>  product(id: &quot;1&quot;) {<br>    id<br>    name<br>    price<br>    reviews {<br>      rating<br>      comment<br>    }<br>  }<br>}</pre><blockquote><strong><em>Screenshot:</em></strong><em> Querying a single product with reviews</em></blockquote><h4>Apollo Sandbox Features to Explore</h4><ul><li><strong>Auto-completion</strong> — Press Ctrl+Space in the query editor to see available fields and types</li><li><strong>Query History</strong> — Click the clock icon (🕐) in the left sidebar to view previously executed queries</li><li><strong>Variables</strong> — Use the <strong>Variables</strong> tab below the query editor to pass dynamic values</li><li><strong>Headers</strong> — Click <strong>Headers</strong> to add custom HTTP headers (e.g., authentication tokens)</li><li><strong>Schema Docs</strong> — Click any type or field in the schema to see its documentation</li></ul><h3>8.4 Quick Verification Checklist</h3><p>Use this checklist to confirm everything is working:</p><pre># 1. All pods are running<br>kubectl get pods<br># All pods should show STATUS = Running</pre><pre># 2. Router has an external IP<br>kubectl get service router-service<br># EXTERNAL-IP should be an IP address (not &lt;pending&gt;)</pre><pre># 3. CURL returns federated data<br>curl -s -X POST \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;query&quot;: &quot;{ products { id name reviews { rating } } }&quot;}&#39; \<br>  <a href="http://external_ip/">http://EXTERNAL_IP</a> | jq .<br># Should return JSON with products containing reviews</pre><pre># 4. Apollo Sandbox connects successfully<br># Open <a href="https://studio.apollographql.com/sandbox">https://studio.apollographql.com/sandbox</a><br># Enter your router URL and verify schema loads</pre><h3>9. Troubleshooting</h3><h3>ImagePullBackOff / ErrImagePull</h3><p><strong>Error:</strong> no match for platform in manifest: not found</p><p><strong>Cause:</strong> The Docker image was built for a different architecture (e.g., linux/arm64 on macOS) than the GKE nodes (linux/amd64).</p><p><strong>Fix:</strong> Rebuild with the correct platform flag:</p><pre>docker buildx build --platform linux/amd64 -t gcr.io/PROJECT_ID/IMAGE:TAG --push .</pre><h3>CrashLoopBackOff — Cannot find module &#39;graphql-tag&#39;</h3><p><strong>Cause:</strong> The graphql-tag package was not listed in package.json dependencies but is required by the application code.</p><p><strong>Fix:</strong> Add graphql-tag to package.json dependencies and rebuild the Docker image:</p><pre># In package.json, add to dependencies:<br>&quot;graphql-tag&quot;: &quot;^2.12.6&quot;</pre><pre># Then rebuild and push<br>docker buildx build --no-cache --platform linux/amd64 \<br>    -t gcr.io/PROJECT_ID/IMAGE:TAG --push .</pre><h3>CrashLoopBackOff — Unknown directive &quot;@external&quot;</h3><p><strong>Cause:</strong> The GraphQL schema uses federation directives (@external) that are not imported in the @link directive.</p><p><strong>Fix:</strong> Add the missing directive to the @link import list in your schema:</p><pre>extend schema @link(<br>  url: &quot;https://specs.apollo.dev/federation/v2.7&quot;,<br>  import: [&quot;@key&quot;, &quot;@external&quot;]<br>)</pre><h3>Container exec format error</h3><p><strong>Cause:</strong> Docker Buildx attestation manifests can confuse containerd on GKE nodes.</p><p><strong>Fix:</strong> Build without attestations:</p><pre>docker buildx build --provenance=false --sbom=false \<br>    --platform linux/amd64 -t gcr.io/PROJECT_ID/IMAGE:TAG --push .</pre><h3>10. Clean up resources</h3><p>When you are done, delete the GKE cluster:</p><pre>gcloud container clusters delete federation-demo-cluster --zone us-central1-a</pre><p>You can also remove the Docker images from GCR if desired:</p><pre>gcloud container images delete gcr.io/YOUR_PROJECT_ID/subgraph-products:1.0.3 --quiet<br>gcloud container images delete gcr.io/YOUR_PROJECT_ID/subgraph-reviews:1.0.3 --quiet</pre><h3>Useful Commands</h3><pre># View pod logs<br>kubectl logs &lt;pod-name&gt;</pre><pre># View logs for a specific app<br>kubectl logs -l app=products<br>kubectl logs -l app=reviews</pre><pre># Describe a pod for debugging<br>kubectl describe pod &lt;pod-name&gt;</pre><pre># Delete all pods (they will be recreated by ReplicaSets)<br>kubectl delete pods --all</pre><pre># Rollout status<br>kubectl rollout status deployment/products-deployment<br>kubectl rollout status deployment/reviews-deployment</pre><pre># Scale deployment<br>kubectl scale deployment/products-deployment --replicas=3</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab2fde80b440" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Spanner Database Schema Changes — CI/CD with GitHub Actions]]></title>
            <link>https://medium.com/@suneelr.kandali/google-spanner-database-schema-changes-ci-cd-7e60fcc8288c?source=rss-32a9b3ac847------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e60fcc8288c</guid>
            <category><![CDATA[liquibase]]></category>
            <category><![CDATA[google-spanner]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Suneel Kandali]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 21:39:11 GMT</pubDate>
            <atom:updated>2026-06-15T21:56:32.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ft_efpKbvSc3M8RkbgxBCg.png" /></figure><p>A CI/CD pipeline for managing Google Cloud Spanner database schema migrations using <strong>Liquibase</strong> and <strong>GitHub Actions</strong>. This project automates schema deployment to Spanner via ChangeSets defined in XML, with a local emulator for testing and a production-like GCP instance for staging.</p><h3>Prerequisites</h3><p>Before you begin, ensure the following tools are installed on your machine:</p><ul><li><strong>Docker</strong> — Version 20.10+ — Install: brew install --cask docker</li><li><strong>gcloud CLI</strong> — Version 450+ — Install: brew install --cask google-cloud-sdk</li><li><strong>curl</strong> — Any version — Pre-installed on macOS / Linux</li></ul><p>You also need a GCP project (gcp-spannerdb-cicd) with the <strong>Cloud Spanner API</strong> enabled.</p><h3>Getting Started — Clone the Repository</h3><p>To run the code locally, first clone the repository and navigate into the project directory:</p><pre># Clone the repository<br>git clone https://github.com/suneelkandali/gcp-spanner-schemachanges-cicd.git</pre><pre># Navigate into the project directory<br>cd gcp-spanner-schemachanges-cicd</pre><p>If the repository is in a different location or uses SSH, use the appropriate URL:</p><pre># Using SSH (if you have SSH access configured)<br>git clone git@github.com:suneelkandali/gcp-spanner-schemachanges-cicd.git</pre><pre># Navigate into the project directory<br>cd gcp-spanner-schemachanges-cicd</pre><p>After cloning, verify the project files are present:</p><pre>ls -la</pre><p>You should see:</p><ul><li>database/ — Contains changelog.xml and changelog-v1.0.0.xml</li><li>.liquibase.properties — Liquibase configuration</li><li>.github/workflows/deploy-migrations.yaml — CI/CD workflow</li><li>README.md — This documentation file</li></ul><p>Once cloned, you can proceed to <strong>Part 1</strong> (local emulator testing) or <strong>Part 2</strong> (GCP instance testing) to run the migration.</p><h3>Project Structure</h3><pre>gcp-spanner-schemachanges-cicd/<br>├── .github/<br>│   └── workflows/<br>│       └── deploy-migrations.yaml    # GitHub Actions CI/CD workflow<br>├── database/<br>│   ├── changelog.xml                  # Root Liquibase changelog<br>│   └── changelog-v1.0.0.xml          # Version-specific changeSet definitions<br>├── .liquibase.properties              # Liquibase configuration (driver, changelog)<br>├── .gitignore                         # Ignores .jar, secrets, IDE files<br>└── README.md</pre><h3>Key Files Explained</h3><ul><li><strong>.liquibase.properties</strong> — Tells Liquibase which changelog file to use (database/changelog.xml) and which JDBC driver to load (com.google.cloud.spanner.jdbc.JdbcDriver).</li><li><strong>database/changelog.xml</strong> — The root changelog that includes versioned changelogs. This is the entry point Liquibase reads.</li><li><strong>database/changelog-v1.0.0.xml</strong> — Contains the actual schema definitions. Each &lt;changeSet&gt; is an atomic migration unit with a unique id and author. Liquibase tracks which changeSets have been applied in a built-in DATABASECHANGELOG table.</li><li><strong>.github/workflows/deploy-migrations.yaml</strong> — Triggers on pushes to main that modify files under database/**. Uses Workload Identity Federation for GCP authentication, downloads the Spanner JDBC driver JAR, and runs liquibase update inside a Docker container.</li></ul><h3>Part 1: Testing with a Local Spanner Emulator</h3><p>The Spanner emulator lets you validate schema changes locally before pushing to GCP. It runs as a Docker container and emulates the Spanner API on localhost.</p><h3>Step 1: Start the Spanner Emulator Container</h3><pre>docker run -d -p 9010:9010 -p 9020:9020 --name spanner-emulator gcr.io/cloud-spanner-emulator/emulator</pre><p><strong>What this does:</strong></p><ul><li>Starts the emulator in detached mode (-d) so it runs in the background.</li><li>Maps port 9010 (gRPC) and port 9020 (REST API).</li><li>Names the container spanner-emulator for easy management.</li></ul><p><strong>Verify it is running:</strong></p><pre>docker ps | grep spanner-emulator</pre><p>You should see output showing the image gcr.io/cloud-spanner-emulator/emulator with ports 9010:9010 and 9020:9020.</p><h3>Step 2: Configure a Local gcloud Context</h3><pre># Create or activate the spanner-local configuration<br>gcloud config configurations create spanner-local || gcloud config configurations activate spanner-local</pre><pre># Disable authentication (the emulator needs no credentials)<br>gcloud config set auth/disable_credentials true</pre><pre># Set a fictitious project name (required by gcloud, not used by the emulator)<br>gcloud config set project mock-project</pre><pre># Override the Spanner API endpoint to point at the local emulator<br>gcloud config set api_endpoint_overrides/spanner <a href="http://localhost:9020/">http://localhost:9020/</a></pre><p><strong>What this does:</strong></p><ul><li>Creates a dedicated gcloud configuration named spanner-local so emulator settings are completely isolated from your default GCP config.</li><li>Disables authentication since the emulator does not require credentials.</li><li>Redirects all gcloud spanner commands to talk to the emulator on port 9020.</li></ul><h3>Step 3: Create the Emulator Instance and Database</h3><pre># Create a Spanner instance in the emulator<br>gcloud spanner instances create test-instance \<br>    --config=emulator-config \<br>    --description=&quot;Local Testing&quot; \<br>    --nodes=1</pre><pre># Create a database inside the instance<br>gcloud spanner databases create test-db --instance=test-instance</pre><p><strong>What this does:</strong></p><ul><li>Creates a single-node instance called test-instance using the built-in emulator-config configuration.</li><li>Creates an empty database called test-db where Liquibase will apply migrations.</li></ul><p><strong>Verify the instance and database exist:</strong></p><pre>gcloud spanner instances list<br>gcloud spanner databases list --instance=test-instance</pre><h3>Step 4: Download the Spanner Liquibase JDBC Driver</h3><pre>curl -L https://github.com/cloudspannerecosystem/liquibase-spanner/releases/download/4.27.0/liquibase-spanner-4.27.0-all.jar \<br>    -o liquibase-spanner-all.jar</pre><p><strong>What this does:</strong></p><ul><li>Downloads the Spanner JDBC driver (bundled with Liquibase support) into your workspace.</li><li>This JAR is mounted into the Liquibase Docker container at runtime.</li></ul><blockquote><strong><em>Note:</em></strong><em> The </em><em>.gitignore already excludes </em><em>*.jar files, so this downloaded JAR will not be committed to version control.</em></blockquote><h3>Step 5: Run the Liquibase Migration Against the Emulator</h3><p>From the project root directory (where database/ and .liquibase.properties are located):</p><pre>docker run --rm \<br>  -v &quot;$PWD&quot;:/liquibase/workspace \<br>  -v &quot;$PWD/liquibase-spanner-all.jar&quot;:/liquibase/internal/lib/liquibase-spanner-all.jar \<br>  --net=host \<br>  liquibase/liquibase:4.27 \<br>  --defaults-file=/liquibase/workspace/.liquibase.properties \<br>  --search-path=/liquibase/workspace \<br>  --url=&quot;jdbc:cloudspanner:/projects/mock-project/instances/test-instance/databases/test-db;autoConfigEmulator=true&quot; \<br>  update</pre><p><strong>What each flag does:</strong></p><ul><li><strong>--rm</strong> — Automatically removes the container after execution</li><li><strong>-v &quot;$PWD&quot;:/liquibase/workspace</strong> — Mounts the project directory so Liquibase can read the changelogs</li><li><strong>-v &quot;$PWD/liquibase-spanner-all.jar&quot;:/liquibase/internal/lib/liquibase-spanner-all.jar</strong> — Injects the Spanner JDBC driver into Liquibase&#39;s classpath</li><li><strong>--net=host</strong> — Lets the container access the emulator on localhost:9020</li><li><strong>--defaults-file=...</strong> — Points to .liquibase.properties for driver and changelog config</li><li><strong>--search-path=...</strong> — Tells Liquibase where to look for changelog files</li><li><strong>--url=jdbc:cloudspanner:...</strong> — The JDBC connection URL with autoConfigEmulator=true to auto-detect the emulator endpoint</li><li><strong>update</strong> — Executes all pending changeSets</li></ul><p><strong>What Liquibase does internally:</strong></p><ol><li>Connects to the emulator via the JDBC URL.</li><li>Creates a DATABASECHANGELOG table (if it does not exist) to track applied changeSets.</li><li>Creates a DATABASECHANGELOGLOCK table to prevent concurrent migrations.</li><li>Reads database/changelog.xml, which includes database/changelog-v1.0.0.xml.</li><li>Applies each changeSet that has not yet been executed.</li></ol><h3>Step 6: Verify the Schema Was Created</h3><pre>gcloud spanner databases execute-sql test-db --instance=test-instance \<br>    --sql=&quot;SELECT table_name FROM information_schema.tables WHERE table_schema = &#39;&#39;&quot;</pre><p><strong>Expected output:</strong></p><pre>TABLE_NAME<br>----------<br>Accounts<br>DATABASECHANGELOG<br>DATABASECHANGELOGLOCK</pre><p>You can also verify the column structure of the Accounts table:</p><pre>gcloud spanner databases execute-sql test-db --instance=test-instance \<br>    --sql=&quot;SELECT column_name, spanner_type, is_nullable FROM information_schema.columns WHERE table_name = &#39;Accounts&#39;&quot;</pre><p><strong>Expected output:</strong></p><pre>COLUMN_NAME          SPANNER_TYPE    IS_NULLABLE<br>AccountId            STRING(36)      NO<br>AccountName          STRING(255)     NO<br>OwnerEmail           STRING(255)     NO<br>CreatedTimestamp     TIMESTAMP       YES</pre><h3>Step 7: Clean Up — Stop the Emulator and Restore gcloud</h3><pre># Stop and remove the emulator container<br>docker stop spanner-emulator<br>docker rm spanner-emulator</pre><pre># Switch gcloud back to the default configuration<br>gcloud config configurations activate default</pre><pre># Unset the emulator-specific overrides<br>gcloud config unset api_endpoint_overrides/spanner<br>gcloud config unset auth/disable_credentials</pre><pre># Set your GCP project<br>gcloud config set project gcp-spannerdb-cicd</pre><p><strong>What this does:</strong></p><ul><li>Stops and removes the emulator Docker container.</li><li>Restores your gcloud CLI to the default configuration so you can interact with real GCP resources.</li><li>Re-enables authentication and removes the API endpoint override.</li></ul><h3>Re-running Migrations on the Emulator</h3><p>If you want to test incremental changes, you can either:</p><p><strong>Option A: Drop and recreate the database (clean slate)</strong></p><pre>gcloud spanner databases delete test-db --instance=test-instance --quiet<br>gcloud spanner databases create test-db --instance=test-instance<br># Then re-run the Liquibase Docker command from Step 5</pre><p><strong>Option B: Let Liquibase apply only new changeSets (incremental)</strong></p><ul><li>Simply modify or add changeSet entries in database/ and re-run the Docker command from Step 5.</li><li>Liquibase’s DATABASECHANGELOG table tracks what has already been applied, so only new or unapplied changeSets will execute.</li></ul><h3>Troubleshooting the Emulator</h3><ul><li><strong>docker: Error response from daemon: port is already allocated</strong> — Run docker ps and stop any existing spanner-emulator container, or use different port mappings.</li><li><strong>gcloud commands return </strong><strong>404 Not Found</strong> — Ensure api_endpoint_overrides/spanner is set to <a href="http://localhost:9020/">http://localhost:9020/.</a></li><li><strong>Connection refused when running Liquibase</strong> — Verify the emulator is running with docker ps, and that --net=host is set.</li><li><strong>DRIVER_NOT_FOUND error</strong> — Ensure the liquibase-spanner-all.jar volume mount path is correct and the file exists in your working directory.</li><li><strong>Liquibase reports </strong><strong>liquibase.exception.LockException</strong> — A previous migration may have crashed, leaving a lock in DATABASECHANGELOGLOCK. Delete and recreate the database (Option A above).</li></ul><h3>Part 2: Testing with a GCP Cloud Spanner Instance</h3><p>This section covers creating a production-like Spanner instance in GCP and running Liquibase migrations against it using your local machine with Application Default Credentials.</p><h3>Step 1: Authenticate with Google Cloud</h3><pre># Log in with your Google Cloud account<br>gcloud auth login</pre><pre># Log in with Application Default Credentials (used by the JDBC driver in Docker)<br>gcloud auth application-default login</pre><pre># Set the target project<br>gcloud config set project gcp-spannerdb-cicd</pre><p><strong>What this does:</strong></p><ul><li>gcloud auth login — Authenticates the gcloud CLI for managing GCP resources (instances, databases, IAM).</li><li>gcloud auth application-default login — Creates Application Default Credentials (ADC) at ~/.config/gcloud/application_default_credentials.json, which the Spanner JDBC driver inside Docker will use for authentication.</li><li>Sets the active GCP project to gcp-spannerdb-cicd.</li></ul><h3>Step 2: Enable Required APIs (if not already enabled)</h3><pre>gcloud services enable spanner.googleapis.com<br>gcloud services enable iamcredentials.googleapis.com --project=gcp-spannerdb-cicd</pre><p><strong>What this does:</strong></p><ul><li>Enables the <strong>Cloud Spanner API</strong> so you can create instances and databases.</li><li>Enables the <strong>IAM Credentials API</strong> (iamcredentials.googleapis.com) which is required for Workload Identity Federation. Without this API, the gcloud iam service-accounts and workload identity pool commands will fail.</li></ul><h3>Step 3: Create a Spanner Instance in GCP</h3><pre>gcloud spanner instances create prod-like-instance \<br>    --config=regional-us-central1 \<br>    --description=&quot;GitOps Migration Test Instance&quot; \<br>    --processing-units=100</pre><p><strong>What this does:</strong></p><ul><li>Creates a Spanner instance named prod-like-instance in the us-central1 region.</li><li>Uses 100 processing units (1/10 of a node), which is the minimum for a cost-effective test instance.</li></ul><p><strong>Verify the instance was created:</strong></p><pre>gcloud spanner instances list</pre><p><strong>Expected output:</strong></p><pre>NAME                    DISPLAY_NAME                      NODE_COUNT  PROCESSING_UNITS  STATE<br>prod-like-instance      GitOps Migration Test Instance    0           100               READY</pre><h3>Step 4: Create the Target Database</h3><pre>gcloud spanner databases create target-app-db \<br>    --instance=prod-like-instance \<br>    --database-dialect=GOOGLE_STANDARD_SQL</pre><p><strong>Verify the database was created:</strong></p><pre>gcloud spanner databases list --instance=prod-like-instance</pre><p><strong>Expected output:</strong></p><pre>DATABASE_ID<br>target-app-db</pre><h3>Step 5: Download the Spanner Liquibase JDBC Driver</h3><p>If you did not already download it during local testing:</p><pre>curl -L https://github.com/cloudspannerecosystem/liquibase-spanner/releases/download/4.27.0/liquibase-spanner-4.27.0-all.jar \<br>    -o liquibase-spanner-all.jar</pre><h3>Step 6: Dry Run — Preview SQL Without Executing</h3><p>Before applying changes to the GCP instance, you can preview what SQL Liquibase would execute:</p><pre>docker run --rm \<br>  -v &quot;$PWD&quot;:/liquibase/workspace \<br>  -v &quot;$PWD/liquibase-spanner-all.jar&quot;:/liquibase/internal/lib/liquibase-spanner-all.jar \<br>  -v &quot;$HOME/.config/gcloud/application_default_credentials.json&quot;:/liquibase/gcp-creds.json \<br>  -e GOOGLE_APPLICATION_CREDENTIALS=/liquibase/gcp-creds.json \<br>  --net=host \<br>  liquibase/liquibase:4.27 \<br>  --defaults-file=/liquibase/workspace/.liquibase.properties \<br>  --search-path=/liquibase/workspace \<br>  --url=&quot;jdbc:cloudspanner:/projects/gcp-spannerdb-cicd/instances/prod-like-instance/databases/target-app-db&quot; \<br>  update-sql</pre><p><strong>What </strong><strong>update-sql does:</strong></p><ul><li>Generates the SQL statements that Liquibase would execute for each pending changeSet.</li><li>Prints them to stdout <strong>without actually executing them</strong>.</li><li>This is useful for code review and auditing before applying changes to a real database.</li></ul><p><strong>Key differences from the emulator command:</strong></p><ul><li>No autoConfigEmulator=true in the JDBC URL (this is a real Spanner instance).</li><li>Mounts application_default_credentials.json into the container and sets the GOOGLE_APPLICATION_CREDENTIALS environment variable for authentication.</li><li>Uses update-sql instead of update for a dry run.</li></ul><h3>Step 7: Apply Migrations to the GCP Instance</h3><p>After reviewing the dry run output, apply the changes for real:</p><pre>docker run --rm \<br>  -v &quot;$PWD&quot;:/liquibase/workspace \<br>  -v &quot;$PWD/liquibase-spanner-all.jar&quot;:/liquibase/internal/lib/liquibase-spanner-all.jar \<br>  -v &quot;$HOME/.config/gcloud/application_default_credentials.json&quot;:/liquibase/gcp-creds.json \<br>  -e GOOGLE_APPLICATION_CREDENTIALS=/liquibase/gcp-creds.json \<br>  --net=host \<br>  liquibase/liquibase:4.27 \<br>  --defaults-file=/liquibase/workspace/.liquibase.properties \<br>  --search-path=/liquibase/workspace \<br>  --url=&quot;jdbc:cloudspanner:/projects/gcp-spannerdb-cicd/instances/prod-like-instance/databases/target-app-db&quot; \<br>  update</pre><p><strong>What this does:</strong></p><ul><li>Connects to the real GCP Spanner instance using Application Default Credentials.</li><li>Applies all pending changeSets to the target-app-db database.</li></ul><h3>Step 8: Verify the Schema in GCP</h3><pre># List tables<br>gcloud spanner databases execute-sql target-app-db --instance=prod-like-instance \<br>    --sql=&quot;SELECT table_name FROM information_schema.tables WHERE table_schema = &#39;&#39;&quot;</pre><pre># List columns of the Accounts table<br>gcloud spanner databases execute-sql target-app-db --instance=prod-like-instance \<br>    --sql=&quot;SELECT column_name, spanner_type, is_nullable FROM information_schema.columns WHERE table_name = &#39;Accounts&#39;&quot;</pre><pre># Check applied changeSets in Liquibase&#39;s tracking table<br>gcloud spanner databases execute-sql target-app-db --instance=prod-like-instance \<br>    --sql=&quot;SELECT id, author, filename, dateexecuted, orderexecuted FROM DATABASECHANGELOG&quot;</pre><h3>Cleanup — Remove the GCP Instance (Optional)</h3><p>To avoid ongoing costs, delete the test instance when you are done:</p><pre># Delete the database first<br>gcloud spanner databases delete target-app-db --instance=prod-like-instance --quiet</pre><pre># Then delete the instance<br>gcloud spanner instances delete prod-like-instance --quiet</pre><h3>Troubleshooting GCP Instance Testing</h3><ul><li><strong>PermissionDenied: ... has not been granted</strong> — Ensure your account has roles/spanner.databaseAdmin or roles/spanner.databaseUser on the project.</li><li><strong>FAILED_PRECONDITION: ... API not enabled</strong> — Run gcloud services enable spanner.googleapis.com.</li><li><strong>UNAUTHENTICATED or credential errors inside Docker</strong> — Ensure you ran gcloud auth application-default login and that the volume mount for application_default_credentials.json uses the correct path.</li><li><strong>AlreadyExists: Database or instance already exists</strong> — Use a different instance/database name, or delete the existing one first.</li><li><strong>Liquibase </strong><strong>LockException on GCP</strong> — This usually means a previous migration crashed. Liquibase&#39;s DATABASECHANGELOGLOCK table is stuck. You can manually clear it by running: gcloud spanner databases execute-sql target-app-db --instance=prod-like-instance --sql=&quot;DELETE FROM DATABASECHANGELOGLOCK WHERE ID = 1&quot;</li></ul><h3>Part 3: CI/CD Pipeline (GitHub Actions)</h3><p>The GitHub Actions workflow automatically applies schema migrations when changes are pushed to the main branch.</p><h3>How It Works</h3><ol><li><strong>Trigger:</strong> A push to main that modifies files under database/**.</li><li><strong>Authentication:</strong> Uses <strong>Workload Identity Federation</strong> (no service account keys stored as secrets).</li><li><strong>Driver Download:</strong> Downloads the liquibase-spanner-4.27.0-all.jar into liquibase-libs/.</li><li><strong>Migration:</strong> Runs liquibase update inside a liquibase/liquibase:4.27 Docker container, targeting prod-like-instance/target-app-db.</li></ol><h3>GCP Service Account Setup (Required Before First Run)</h3><p>Before running these commands, ensure the IAM Credentials API is enabled:</p><pre>gcloud services enable iamcredentials.googleapis.com --project=gcp-spannerdb-cicd</pre><p>Run these commands once to set up the service account and Workload Identity Federation:</p><pre># 1. Create the service account<br>gcloud iam service-accounts create spanner-migrator \<br>    --description=&quot;Service account for GitHub Actions Spanner migrations&quot; \<br>    --display-name=&quot;Spanner Migrator&quot;</pre><pre># 2. Grant Database Admin role on Spanner<br>gcloud projects add-iam-policy-binding gcp-spannerdb-cicd \<br>    --member=&quot;serviceAccount:spanner-migrator@gcp-spannerdb-cicd.iam.gserviceaccount.com&quot; \<br>    --role=&quot;roles/spanner.databaseAdmin&quot;</pre><pre># 3. Create a Workload Identity Pool for GitHub<br>gcloud iam workload-identity-pools create github-pool \<br>    --location=&quot;global&quot; \<br>    --display-name=&quot;GitHub Actions Pool&quot;</pre><pre># 4. Create an OIDC provider within the pool<br>gcloud iam workload-identity-pools providers create-oidc github-provider \<br>    --location=&quot;global&quot; \<br>    --workload-identity-pool=&quot;github-pool&quot; \<br>    --display-name=&quot;GitHub Provider&quot; \<br>    --attribute-mapping=&quot;google.subject=assertion.sub,attribute.repository=assertion.repository&quot; \<br>    --attribute-condition=&quot;assertion.repository == &#39;suneelkandali/gcp-spanner-schemachanges-cicd&#39;&quot; \<br>    --issuer-uri=&quot;https://token.actions.githubusercontent.com&quot;</pre><pre># 5. Bind the service account to the GitHub repository via Workload Identity<br>gcloud iam service-accounts add-iam-policy-binding spanner-migrator@gcp-spannerdb-cicd.iam.gserviceaccount.com \<br>    --role=&quot;roles/iam.workloadIdentityUser&quot; \<br>    --member=&quot;principalSet://iam.googleapis.com/projects/947330204934/locations/global/workloadIdentityPools/github-pool/attribute.repository/suneelkandali/gcp-spanner-schemachanges-cicd&quot;</pre><h3>Workflow File Reference</h3><p>The complete workflow at .github/workflows/deploy-migrations.yaml is shown below, followed by a detailed breakdown of each step.</p><pre>name: Execute Spanner Migrations</pre><pre>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br>    paths:<br>      - &#39;database/**&#39;</pre><pre>jobs:<br>  run-migration:<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: &#39;read&#39;<br>      id-token: &#39;write&#39;</pre><pre>    steps:<br>    - name: Checkout Code<br>      uses: actions/checkout@v4</pre><pre>    - name: Authenticate to Google Cloud<br>      id: auth<br>      uses: google-github-actions/auth@v2<br>      with:<br>        workload_identity_provider: &#39;projects/1234567890/locations/global/workloadIdentityPools/github-pool/providers/github-provider&#39;<br>        service_account: &#39;spanner-migrator@gcp-spannerdb-cicd.iam.gserviceaccount.com&#39;</pre><pre>    - name: Download Cloud Spanner Liquibase Extension<br>      run: |<br>        mkdir -p liquibase-libs<br>        curl -L <a href="https://github.com/cloudspannerecosystem/liquibase-spanner/releases/download/4.27.0/liquibase-spanner-4.27.0-all.jar">https://github.com/cloudspannerecosystem/liquibase-spanner/releases/download/4.27.0/liquibase-spanner-4.27.0-all.jar</a> -o liquibase-libs/liquibase-spanner-all.jar</pre><pre>    - name: Run Liquibase Migration<br>      uses: docker://liquibase/liquibase:4.27<br>      env:<br>        GOOGLE_APPLICATION_CREDENTIALS: ${{ steps.auth.outputs.credentials_file_path }}<br>      with:<br>        args: &gt;<br>          --changelog-file=database/changelog.xml<br>          --search-path=${{ github.workspace }}<br>          --classpath=${{ github.workspace }}/liquibase-libs/liquibase-spanner-all.jar<br>          --url=jdbc:cloudspanner:/projects/gcp-spannerdb-cicd/instances/prod-like-instance/databases/target-app-db<br>          update</pre><h3>Detailed Breakdown of Each Workflow Step</h3><p>The following explains every configuration option and its relationship to the project, Spanner instance, and database name.</p><h4>Trigger Configuration</h4><pre>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br>    paths:<br>      - &#39;database/**&#39;</pre><ul><li><strong>branches</strong> — [&quot;main&quot;] — The workflow only runs when code is pushed to the main branch.</li><li><strong>paths</strong> — [&quot;database/**&quot;] — The workflow only triggers when files under the database/ directory are changed (e.g., database/changelog.xml, database/changelog-v1.0.0.xml).</li></ul><p><strong>Why this matters:</strong> This means schema changes are automatically deployed on every push to main that touches a changelog file. A push that only changes .github/ or other files will <strong>not</strong> trigger the migration.</p><p>You must update the paths filter if you add other directories that contain migration files (e.g., migrations/**).</p><h4>Job Configuration</h4><pre>jobs:<br>  run-migration:<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: &#39;read&#39;<br>      id-token: &#39;write&#39;</pre><ul><li><strong>runs-on</strong> — ubuntu-latest — The workflow runs on the latest Ubuntu GitHub-hosted runner.</li><li><strong>permissions.contents</strong> — read — The workflow can read the repository (e.g., checkout code).</li><li><strong>permissions.id-token</strong> — write — <strong>Required for Workload Identity Federation.</strong> This allows the runner to request an OIDC token from GitHub, which is exchanged for a GCP access token.</li></ul><h4>Step 1: Checkout Code</h4><pre>- name: Checkout Code<br>  uses: actions/checkout@v4</pre><p><strong>What it does:</strong></p><ul><li>Clones the repository to the runner’s workspace.</li><li>The repository root becomes ${{ github.workspace }} (e.g., /home/runner/work/gcp-spanner-schemachanges-cicd/gcp-spanner-schemachanges-cicd/).</li><li>This checkout includes all database/ files that were changed in the push.</li></ul><p><strong>Why it’s needed:</strong></p><ul><li>Liquibase needs access to database/changelog.xml and all referenced changelog files (database/changelog-v1.0.0.xml).</li><li>The .liquibase.properties file is also needed.</li></ul><h4>Step 2: Authenticate to Google Cloud</h4><pre>- name: Authenticate to Google Cloud<br>  id: auth<br>  uses: google-github-actions/auth@v2<br>  with:<br>    workload_identity_provider: &#39;projects/1234567890/locations/global/workloadIdentityPools/github-pool/providers/github-provider&#39;<br>    service_account: &#39;spanner-migrator@gcp-spannerdb-cicd.iam.gserviceaccount.com&#39;</pre><ul><li><strong>id</strong> — auth — A step identifier used to reference the auth output later (e.g., ${{ steps.auth.outputs.credentials_file_path }}).</li><li><strong>uses</strong> — google-github-actions/auth@v2 — The official Google GitHub Action for GCP authentication.</li><li><strong>workload_identity_provider</strong> — projects/1234567890/locations/global/workloadIdentityPools/github-pool/providers/github-provider — The full resource path of the OIDC provider that GitHub Actions uses to authenticate with GCP. <strong>Replace </strong><strong>1234567890 with your GCP project number.</strong></li><li><strong>service_account</strong> — spanner-migrator@gcp-spannerdb-cicd.iam.gserviceaccount.com — The GCP service account that the workflow impersonates. This service account must have roles/spanner.databaseAdmin on the project.</li></ul><p><strong>How Workload Identity Federation works (no keys needed):</strong></p><ol><li>GitHub Actions generates an OIDC token for the workflow run.</li><li>The auth action sends this OIDC token to GCP.</li><li>GCP validates the token against the OIDC provider (github-provider) and the pool (github-pool).</li><li>If valid, GCP issues a short-lived access token for the spanner-migrator service account.</li><li>The access token is stored as steps.auth.outputs.credentials_file_path (a temporary credential file).</li></ol><p><strong>This is why </strong><strong>id-token: write permission is required</strong> in the job configuration.</p><h4>Step 3: Download the Spanner Liquibase Extension</h4><pre>- name: Download Cloud Spanner Liquibase Extension<br>  run: |<br>    mkdir -p liquibase-libs<br>    curl -L https://github.com/cloudspannerecosystem/liquibase-spanner/releases/download/4.27.0/liquibase-spanner-4.27.0-all.jar -o liquibase-libs/liquibase-spanner-all.jar</pre><p><strong>What it does:</strong></p><ul><li>Creates a liquibase-libs/ directory in the workspace.</li><li>Downloads the liquibase-spanner-4.27.0-all.jar from GitHub Releases.</li><li>This JAR contains the Spanner JDBC driver that Liquibase needs to connect to Spanner.</li></ul><p><strong>Why it’s a separate step:</strong></p><ul><li>The Liquibase Docker image (liquibase/liquibase:4.27) does <strong>not</strong> include the Spanner driver by default.</li><li>Without this JAR, Liquibase will fail with a DRIVER_NOT_FOUND error because it cannot load com.google.cloud.spanner.jdbc.JdbcDriver.</li></ul><p><strong>JAR version alignment:</strong></p><ul><li>The workflow uses 4.27.0 to match the Docker image liquibase/liquibase:4.27.</li><li>The JAR is the all variant (bundled with all dependencies).</li></ul><h4>Step 4: Run Liquibase Migration</h4><pre>- name: Run Liquibase Migration<br>  uses: docker://liquibase/liquibase:4.27<br>  env:<br>    GOOGLE_APPLICATION_CREDENTIALS: ${{ steps.auth.outputs.credentials_file_path }}<br>  with:<br>    args: &gt;<br>      --changelog-file=database/changelog.xml<br>      --search-path=${{ github.workspace }}<br>      --classpath=${{ github.workspace }}/liquibase-libs/liquibase-spanner-all.jar<br>      --url=jdbc:cloudspanner:/projects/gcp-spannerdb-cicd/instances/prod-like-instance/databases/target-app-db<br>      update</pre><ul><li><strong>uses</strong> — docker://liquibase/liquibase:4.27 — Runs the official Liquibase Docker image directly (no need for a separate docker run command).</li><li><strong>env.GOOGLE_APPLICATION_CREDENTIALS</strong> — ${{ steps.auth.outputs.credentials_file_path }} — Points the JDBC driver to the temporary credential file generated by the auth step. This is how the driver authenticates with Spanner.</li><li><strong>--changelog-file</strong> — database/changelog.xml — The root changelog file that Liquibase reads. This is relative to the repository root.</li><li><strong>--search-path</strong> — ${{ github.workspace }} — The directory where Liquibase searches for changelog files and other resources. Points to the repository root on the runner.</li><li><strong>--classpath</strong> — ${{ github.workspace }}/liquibase-libs/liquibase-spanner-all.jar — Adds the Spanner JDBC driver JAR to Liquibase&#39;s classpath so it can load com.google.cloud.spanner.jdbc.JdbcDriver.</li><li><strong>--url</strong> — jdbc:cloudspanner:/projects/gcp-spannerdb-cicd/instances/prod-like-instance/databases/target-app-db — The JDBC connection URL that specifies the <strong>project</strong> (gcp-spannerdb-cicd), <strong>instance</strong> (prod-like-instance), and <strong>database</strong> (target-app-db).</li><li><strong>update</strong> — Tells Liquibase to apply all pending changeSets.</li></ul><p><strong>How the JDBC URL is structured:</strong></p><pre>jdbc:cloudspanner:/projects/gcp-spannerdb-cicd/instances/prod-like-instance/databases/target-app-db<br> │        │         │                          │                          │<br> │        │         │                          │                          └── Database name<br> │        │         │                          └── Instance name<br> │        │         └── GCP Project ID<br> │        └── Database protocol<br> └── JDBC driver scheme</pre><ul><li><strong>Project:</strong> gcp-spannerdb-cicd — The GCP project that owns the Spanner instance.</li><li><strong>Instance:</strong> prod-like-instance — The Spanner instance created in Part 2, Step 3.</li><li><strong>Database:</strong> target-app-db — The database created in Part 2, Step 4.</li></ul><p><strong>What happens when the migration runs:</strong></p><ol><li>The Liquibase container starts inside the GitHub Actions runner.</li><li>It authenticates using the temporary GCP credentials.</li><li>It reads database/changelog.xml, which includes database/changelog-v1.0.0.xml.</li><li>It connects to the target-app-db database in the prod-like-instance instance.</li><li>It checks for any unapplied changeSets by querying the DATABASECHANGELOG table.</li><li>For each unapplied changeSet, it executes the corresponding SQL statements.</li><li>Records each applied changeSet in the DATABASECHANGELOG table.</li><li>Exits with status 0 (success) or nonzero (failure).</li></ol><h3>Steps Required to Customize deploy-migrations.yaml for Your Project</h3><p>When setting up this workflow for your own GCP Spanner project, you must update the following values:</p><ul><li><strong>GCP Project ID</strong> — Location in YAML: --url=jdbc:cloudspanner:/projects/&lt;PROJECT_ID&gt;/... — Run gcloud config get project to get your project ID.</li><li><strong>GCP Project Number</strong> — Location in YAML: workload_identity_provider: &#39;projects/&lt;PROJECT_NUMBER&gt;/...&#39; — Run gcloud projects describe &lt;PROJECT_ID&gt; --format=&#39;value(projectNumber)&#39; to get the numeric project number.</li><li><strong>Spanner Instance Name</strong> — Location in YAML: --url=.../instances/&lt;INSTANCE_NAME&gt;/... — Run gcloud spanner instances list to get the instance name. The workflow uses prod-like-instance by default.</li><li><strong>Database Name</strong> — Location in YAML: --url=.../databases/&lt;DATABASE_NAME&gt; — Run gcloud spanner databases list --instance=&lt;INSTANCE_NAME&gt; to get the database name. The workflow uses target-app-db by default.</li><li><strong>Service Account Email</strong> — Location in YAML: service_account: &#39;&lt;SA&gt;@&lt;PROJECT_ID&gt;.iam.gserviceaccount.com&#39; — The email of the service account created with gcloud iam service-accounts create.</li><li><strong>Workload Identity Pool Name</strong> — Location in YAML: workload_identity_provider: &#39;.../workloadIdentityPools/&lt;POOL_NAME&gt;/...&#39; — The pool name created with gcloud iam workload-identity-pools create.</li><li><strong>GitHub Repository</strong> — Location in YAML: attribute-condition: &quot;assertion.repository == &#39;&lt;OWNER&gt;/&lt;REPO&gt;&#39;&quot; — The full GitHub repository path (e.g., suneelkandali/gcp-spanner-schemachanges-cicd).</li></ul><h3>Example: Customizing for a Different Instance and Database</h3><p>If you want to target a different Spanner instance (e.g., staging-instance) and database (e.g., staging-db), update the --url argument in the workflow:</p><pre>- name: Run Liquibase Migration<br>  uses: docker://liquibase/liquibase:4.27<br>  env:<br>    GOOGLE_APPLICATION_CREDENTIALS: ${{ steps.auth.outputs.credentials_file_path }}<br>  with:<br>    args: &gt;<br>      --changelog-file=database/changelog.xml<br>      --search-path=${{ github.workspace }}<br>      --classpath=${{ github.workspace }}/liquibase-libs/liquibase-spanner-all.jar<br>      --url=jdbc:cloudspanner:/projects/gcp-spannerdb-cicd/instances/staging-instance/databases/staging-db<br>      update</pre><p><strong>Important:</strong> The instance (staging-instance) and database (staging-db) must already exist in GCP before the workflow runs. The workflow does <strong>not</strong> create instances or databases — it only applies schema changes.</p><h3>Mapping the Workflow to the Local Emulator</h3><p>To understand how the workflow maps to the local emulator testing in Part 1, here is the equivalent mapping:</p><ul><li><strong>--url</strong> — Workflow: jdbc:cloudspanner:/projects/gcp-spannerdb-cicd/instances/prod-like-instance/databases/target-app-db — Emulator: jdbc:cloudspanner:/projects/mock-project/instances/test-instance/databases/test-db;autoConfigEmulator=true</li><li><strong>GOOGLE_APPLICATION_CREDENTIALS</strong> — Workflow: Required — Emulator: Not needed (emulator has no auth)</li><li><strong>--classpath</strong> — Workflow: liquibase-libs/liquibase-spanner-all.jar — Emulator: -v &quot;$PWD/liquibase-spanner-all.jar&quot;:/liquibase/internal/lib/liquibase-spanner-all.jar</li><li><strong>--search-path</strong> — Workflow: ${{ github.workspace }} — Emulator: -v &quot;$PWD&quot;:/liquibase/workspace + --search-path=/liquibase/workspace</li><li><strong>--changelog-file</strong> — Workflow: database/changelog.xml — Emulator: --defaults-file=/liquibase/workspace/.liquibase.properties</li></ul><p>The key differences between the workflow and local testing are:</p><ol><li><strong>Authentication:</strong> The workflow uses GOOGLE_APPLICATION_CREDENTIALS with Workload Identity-fed credentials; the emulator uses no credentials.</li><li><strong>URL:</strong> The workflow uses the real GCP Spanner JDBC URL; the emulator uses autoConfigEmulator=true.</li><li><strong>Execution:</strong> The workflow runs in a GitHub-hosted runner; local testing runs in a Docker container on your machine.</li></ol><h3>Making New Schema Changes</h3><p>Follow this workflow when adding or modifying database schemas:</p><ol><li><strong>Create or edit a changelog file</strong> in the database/ directory. For a new version, create database/changelog-v1.1.0.xml and include it from changelog.xml:</li></ol><ul><li>&lt;include file=&quot;database/changelog-v1.1.0.xml&quot;/&gt;</li></ul><ol><li><strong>Define your changeSets</strong> with unique id values and an author tag:</li></ol><ul><li>&lt;changeSet id=&quot;20260616-01&quot; author=&quot;platform-eng&quot;&gt; &lt;createTable tableName=&quot;Orders&quot;&gt; &lt;column name=&quot;OrderId&quot; type=&quot;VARCHAR(36)&quot;&gt; &lt;constraints primaryKey=&quot;true&quot; nullable=&quot;false&quot;/&gt; &lt;/column&gt; &lt;column name=&quot;AccountId&quot; type=&quot;VARCHAR(36)&quot;/&gt; &lt;column name=&quot;Amount&quot; type=&quot;INT64&quot;/&gt; &lt;/createTable&gt; &lt;/changeSet&gt;</li></ul><ol><li><strong>Test locally</strong> with the emulator (see Part 1).</li><li><strong>Test against GCP</strong> with a dry run (see Part 2, Step 6).</li><li><strong>Commit and push to </strong><strong>main</strong> to trigger the CI/CD pipeline:</li></ol><ul><li>git add database/ git commit -m &quot;feat: add Orders table schema&quot; git push origin main</li></ul><ol><li><strong>Verify</strong> in the GitHub Actions tab that the migration succeeded, and confirm the schema in GCP.</li></ol><h3>Quick Reference — Common Commands</h3><ul><li><strong>Start emulator</strong> — docker run -d -p 9010:9010 -p 9020:9020 --name spanner-emulator gcr.io/cloud-spanner-emulator/emulator</li><li><strong>Stop emulator</strong> — docker stop spanner-emulator &amp;&amp; docker rm spanner-emulator</li><li><strong>Create emulator instance</strong> — gcloud spanner instances create test-instance --config=emulator-config --description=&quot;Local Testing&quot; --nodes=1</li><li><strong>Create emulator database</strong> — gcloud spanner databases create test-db --instance=test-instance</li><li><strong>Download JDBC driver</strong> — curl -L https://github.com/cloudspannerecosystem/liquibase-spanner/releases/download/4.27.0/liquibase-spanner-4.27.0-all.jar -o liquibase-spanner-all.jar</li><li><strong>Run migration (emulator)</strong> — docker run --rm -v &quot;$PWD&quot;:/liquibase/workspace -v &quot;$PWD/liquibase-spanner-all.jar&quot;:/liquibase/internal/lib/liquibase-spanner-all.jar --net=host liquibase/liquibase:4.27 --defaults-file=/liquibase/workspace/.liquibase.properties --search-path=/liquibase/workspace --url=&quot;jdbc:cloudspanner:/projects/mock-project/instances/test-instance/databases/test-db;autoConfigEmulator=true&quot; update</li><li><strong>Dry run (GCP)</strong> — Same as above but with --url=&quot;jdbc:cloudspanner:/projects/gcp-spannerdb-cicd/instances/prod-like-instance/databases/target-app-db&quot;, add credential mounts, and use update-sql</li><li><strong>Run migration (GCP)</strong> — Same as dry run but use update instead of update-sql</li><li><strong>List tables</strong> — gcloud spanner databases execute-sql &lt;db&gt; --instance=&lt;instance&gt; --sql=&quot;SELECT table_name FROM information_schema.tables WHERE table_schema = &#39;&#39;&quot;</li><li><strong>Switch back to default gcloud</strong> — gcloud config configurations activate default &amp;&amp; gcloud config unset api_endpoint_overrides/spanner &amp;&amp; gcloud config unset auth/disable_credentials &amp;&amp; gcloud config set project gcp-spannerdb-cicd</li><li><strong>Delete GCP test instance</strong> — gcloud spanner instances delete prod-like-instance --quiet</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e60fcc8288c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>