<?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 Shahid Raza on Medium]]></title>
        <description><![CDATA[Stories by Shahid Raza on Medium]]></description>
        <link>https://medium.com/@sraza0098?source=rss-50b272340a8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aXf77C3qsaGW75r4</url>
            <title>Stories by Shahid Raza on Medium</title>
            <link>https://medium.com/@sraza0098?source=rss-50b272340a8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:42:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sraza0098/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[We Cut EC2 Compute Costs by ~70% — By Designing for Failure, Not Just Choosing Spot]]></title>
            <link>https://medium.com/@sraza0098/we-cut-ec2-compute-costs-by-70-by-designing-for-failure-not-just-choosing-spot-06adee8c888d?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/06adee8c888d</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[earth-observation]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 10:21:48 GMT</pubDate>
            <atom:updated>2026-09-01T10:21:48.345Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Terraform, SQS, EC2 Auto Scaling and interruption-aware workers turned a large parallel processing workload into a fault-tolerant Spot architecture</h3><p>Cloud cost optimisation often gets reduced to one sentence:</p><blockquote><em>“Use Spot Instances. They’re cheaper.”</em></blockquote><p>That advice is technically correct and operationally incomplete.</p><p>The difficult question is not:</p><p><strong>Can this workload run on Spot?</strong></p><p>It is: <strong>What happens when AWS takes the machine back halfway through your processing?</strong></p><p>That was the question I had to solve while working on a large-scale satellite-data processing pipeline. The workload involved thousands of independent jobs, heavy raster processing, parallel workers, large Zarr outputs and several hours of compute.</p><p>Initially, the workers ran on On-Demand EC2.</p><p>It worked.</p><p>But it was expensive.</p><p>The eventual architecture moved the processing fleet to <strong>100% EC2 Spot</strong>, managed through Terraform, while keeping the workload safe when instances disappeared.</p><p>The result?</p><p><strong>Around 70% lower EC2 compute cost.</strong></p><p>But the cost saving was actually the least interesting part of the engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*mLm4rTuPqfB98xmIab1KCA.png" /><figcaption>Architecture</figcaption></figure><h3>Why This Workload Was Almost Perfect for Spot</h3><p>Each processing job could be described roughly as:</p><pre>Take one job from the queue<br>        ↓<br>Discover source imagery<br>        ↓<br>Filter usable scenes<br>        ↓<br>Process many scenes in parallel<br>        ↓<br>Build the output<br>        ↓<br>Upload to object storage<br>        ↓<br>Mark the job complete</pre><p>The jobs were independent.</p><p>Worker A did not care what Worker B was processing.</p><p>That property is extremely important.</p><p>Instead of having:</p><pre>One giant distributed computation<br>where every node depends on every other node</pre><p>we had:</p><pre>Job 1 → Worker A<br>Job 2 → Worker B<br>Job 3 → Worker C<br>Job 4 → Worker D</pre><p>Amazon SQS sat in the middle as the work coordinator.</p><p>And that changed the Spot problem completely.</p><p>If Worker C disappeared, we did not need to reconstruct the whole distributed computation.</p><p>We only needed:</p><pre>Job 3 → return to SQS → another worker retries it</pre><p>That is a much easier failure model.</p><h3>Terraform: From Fixed EC2 to a Spot Fleet</h3><p>The infrastructure already used an EC2 Auto Scaling Group.</p><p>Instead of replacing the architecture, I changed the <strong>purchasing model</strong>.</p><p>A simplified version looked like this:</p><pre>mixed_instances_policy {<br>  instances_distribution {<br>    on_demand_base_capacity                  = 0<br>    on_demand_percentage_above_base_capacity = 0<br>    spot_allocation_strategy = &quot;price-capacity-optimized&quot;<br>  }<br>  launch_template {<br>    launch_template_specification {<br>      launch_template_id = aws_launch_template.worker.id<br>      version            = &quot;$Latest&quot;<br>    }<br>    override {<br>      instance_type = &quot;c8gn.4xlarge&quot;<br>    }<br>  }<br>}<br>capacity_rebalance = true</pre><p>The two most important numbers were:</p><pre>on_demand_base_capacity = 0<br>on_demand_percentage_above_base_capacity = 0</pre><p>A Mixed Instances Policy does <strong>not</strong> mean that you must actually run a mixture of On-Demand and Spot.</p><p>With both values set to zero, our worker fleet was effectively:</p><pre>0% On-Demand<br>100% Spot</pre><p>We also used:</p><pre>spot_allocation_strategy = &quot;price-capacity-optimized&quot;</pre><p>AWS recommends this strategy because it considers both price and available capacity when choosing Spot pools, rather than simply selecting the cheapest possible capacity.</p><h3>Desired Capacity Does Not Mean Guaranteed Capacity</h3><p>This became one of the most interesting lessons.</p><p>Suppose Terraform says:</p><pre>desired_capacity = 10</pre><p>That does <strong>not</strong> mean:</p><blockquote><em>“Do not process anything until ten instances exist.”</em></blockquote><p>It means:</p><blockquote><em>“Try to maintain ten instances.”</em></blockquote><p>So a Spot fleet might look like:</p><pre>Desired: 10<br>Running: 0</pre><p>when capacity is unavailable.</p><p>Later:</p><pre>Desired: 10<br>Running: 3</pre><p>Three workers can immediately start consuming jobs.</p><p>Then:</p><pre>Desired: 10<br>Running: 7</pre><p>And eventually:</p><pre>Desired: 10<br>Running: 10</pre><p>The processing architecture simply consumes whatever compute capacity happens to exist.</p><p>That is a really useful mental model for batch workloads.</p><p>Your infrastructure says:</p><blockquote><em>“I would like ten workers.”</em></blockquote><p>Your application says:</p><blockquote><em>“Give me anything between zero and ten and I will make progress.”</em></blockquote><h3>Terraform Should Not Treat Missing Spot Capacity as a Deployment Failure</h3><p>There was one small but important Terraform detail.</p><p>By default, Terraform waits for an Auto Scaling Group to reach healthy capacity.</p><p>That makes perfect sense for many applications.</p><p>It makes less sense when the architecture intentionally allows:</p><pre>Desired = 10<br>Running = 0</pre><p>because Spot capacity may temporarily be unavailable.</p><p>For this architecture we used:</p><pre>wait_for_capacity_timeout = &quot;0&quot;</pre><p>This disables Terraform’s ASG capacity waiting behaviour.</p><p>Terraform’s responsibility becomes:</p><pre>Configure the ASG correctly.</pre><p>Not:</p><pre>Guarantee that AWS currently has Spot capacity.</pre><p>That distinction matters.</p><h3>The Hard Part: What Happens Mid-Processing?</h3><p>Now imagine one worker is halfway through processing hundreds of satellite scenes.</p><p>Then AWS sends a Spot interruption signal.</p><p>The worst possible implementation would be:</p><pre>Instance disappears<br>        ↓<br>SQS message remains invisible<br>        ↓<br>Partial output remains in storage<br>        ↓<br>System believes output exists<br>        ↓<br>Job never completes correctly</pre><p>So the worker had to become <strong>interruption-aware</strong>.</p><p>We added a watcher that monitored the EC2 metadata service for:</p><ul><li>Spot interruption notices</li><li>EC2 rebalance recommendations</li></ul><p>When either appeared, the worker stopped accepting new work.</p><p>The processor itself ran in its own process group, allowing the worker to terminate the entire processing tree rather than leaving child processes running.</p><p>The flow became:</p><pre>Spot/Rebalance signal<br>        ↓<br>Stop taking new jobs<br>        ↓<br>Terminate processing safely<br>        ↓<br>Mark current attempt as aborted<br>        ↓<br>Release SQS message immediately<br>        ↓<br>Worker exits<br>        ↓<br>Another instance retries the job</pre><p>AWS Capacity Rebalancing can proactively attempt to replace Spot Instances that receive a rebalance recommendation, and AWS specifically highlights graceful shutdown of SQS workers as a relevant use case.</p><p>This is where SQS made Spot dramatically easier.</p><p>We did not need to invent a distributed retry coordinator.</p><p>The queue already was the coordinator.</p><h3>Partial Outputs Were More Dangerous Than Interrupted Compute</h3><p>There was another subtle problem.</p><p>Imagine a worker uploads 30 files belonging to a Zarr dataset.</p><p>The dataset actually contains 40 files.</p><p>Then the instance disappears.</p><p>A naive check might ask:</p><pre>Does this S3 prefix exist?</pre><p>The answer is:</p><pre>Yes.</pre><p>But the dataset is corrupt or incomplete.</p><p>So instead of treating “some files exist” as success, the worker wrote a final marker only <strong>after every output object had uploaded successfully</strong>.</p><p>Conceptually:</p><pre>Upload file 1<br>Upload file 2<br>...<br>Upload file 40<br>        ↓<br>Everything succeeded?<br>        ↓<br>Write completion marker</pre><p>If the machine disappeared before that final step, another worker knew the output was incomplete and could safely retry it.</p><p>This small pattern turned out to be just as important as the Spot interruption handling itself.</p><h3>Parallelism Still Happened Inside Every Spot Worker</h3><p>The Auto Scaling Group provided <strong>horizontal parallelism</strong>:</p><pre>Worker<br>Worker<br>Worker<br>Worker</pre><p>But each machine also performed significant parallel work internally.</p><p>A simplified pipeline looked like:</p><pre>STAC discovery<br>        ↓<br>metadata / scene filtering<br>        ↓<br>ThreadPoolExecutor<br>        ↓<br>scene processing<br>        ↓<br>ProcessPoolExecutor<br>        ↓<br>parallel object upload</pre><p>For example, metadata filtering could use dozens of threads while CPU-heavy scene processing used multiple processes.</p><p>So increasing the Auto Scaling Group from 1 to 10 workers was not simply:</p><pre>10 tasks instead of 1</pre><p>It was closer to:</p><pre>10 independently parallel processing engines</pre><p>That is why benchmarking an instance type before putting many of them into the fleet matters.</p><h3>Mixed Instances Policies Become Much More Interesting After Benchmarking</h3><p>During this run I deliberately started with one instance type.</p><p>That gave us consistent performance measurements.</p><p>Once you know things such as:</p><pre>Instance A<br>Average tile: 5 minutes<br>Cost: X/hour<br>Instance B<br>Average tile: 6 minutes<br>Cost: Y/hour<br>Instance C<br>Average tile: 4 minutes<br>Cost: Z/hour</pre><p>you can stop asking:</p><blockquote><em>“Which EC2 instance is cheapest per hour?”</em></blockquote><p>and instead ask:</p><blockquote><strong><em>“Which instance gives the best cost per completed unit of work?”</em></strong></blockquote><p>That is a much better metric.</p><p>Once several compatible instance types have been benchmarked, a Mixed Instances Policy can expose all of them:</p><pre>override {<br>  instance_type = &quot;type-a&quot;<br>}<br>override {<br>  instance_type = &quot;type-b&quot;<br>}<br>override {<br>  instance_type = &quot;type-c&quot;<br>}</pre><p>Now price-capacity-optimized has multiple Spot capacity pools from which to choose. AWS recommends using multiple instance types and Availability Zones when building mixed Spot groups because this increases capacity flexibility.</p><p>This also solves a problem we experienced in practice.</p><p>At one point:</p><pre>Desired capacity: 3<br>Running capacity: 0</pre><p>There simply wasn’t enough Spot capacity for our chosen instance type.</p><p>Nothing was wrong with Terraform.</p><p>Nothing was wrong with the worker.</p><p>The capacity did not exist.</p><p>With a sufficiently benchmarked set of equivalent instance types, the fleet could instead obtain capacity from another compatible pool.</p><p>That is where Mixed Instances Policies become really powerful.</p><h3>So… How Much Did Spot Actually Save?</h3><p>The production numbers made the result fairly clear.</p><p>Rounded figures from the run were approximately:</p><pre>Actual Spot EC2 compute:<br>~$304<br><br>Estimated equivalent On-Demand compute:<br>~$980</pre><p>Which gives:</p><pre>Estimated saving:<br>~$676<br><br>Compute-cost reduction:<br>~70%</pre><p>In other words:</p><blockquote><strong><em>The Spot fleet cost roughly one-third of what equivalent On-Demand compute would have cost.</em></strong></blockquote><p>These numbers should always be treated carefully because Spot prices vary over time and across Availability Zones.</p><p>But the broader result was unmistakable.</p><p>The saving did not come from making the processing algorithm cheaper.</p><p>The same workload still had to run.</p><p>We changed <strong>how we purchased and orchestrated the compute</strong>.</p><h3>The Bigger Lesson: Spot Is an Application Architecture Problem</h3><p>The biggest thing I took away from this work was that adopting Spot should not begin with pricing.</p><p>It should begin with this question:</p><blockquote><strong><em>Can my application lose a machine at any moment without losing the job?</em></strong></blockquote><p>For us, the pieces lined up nicely:</p><pre>SQS<br>    → durable work queue<br><br>Auto Scaling Group<br>    → elastic compute fleet<br><br>Spot<br>    → inexpensive transient compute<br><br>Interruption watcher<br>    → graceful worker shutdown<br><br>Retryable jobs<br>    → failure recovery<br><br>Completion marker<br>    → protection from partial outputs<br><br>Terraform<br>    → reproducible infrastructure</pre><p>Together they produced something much more valuable than “cheap EC2”.</p><p>They produced a system where <strong>compute became disposable</strong>.</p><p>A worker could appear.</p><p>Process jobs.</p><p>Disappear.</p><p>Be replaced.</p><p>And the pipeline simply continued.</p><p>That is the architecture that made the ~70% saving possible.</p><p>Not Spot pricing alone.</p><h3>Final Thought</h3><p>If your workload consists of independent, retryable, queue-driven jobs, Spot Instances are worth looking at seriously.</p><p>But don’t begin by replacing:</p><pre>On-Demand → Spot</pre><p>and hoping for the best.</p><p>Begin by designing this:</p><pre>machine disappears<br>        ↓<br>nothing important is lost<br>        ↓<br>job safely retries<br>        ↓<br>processing continues</pre><p>Once that works, Spot stops feeling like unreliable infrastructure.</p><p>It starts feeling like what it really is:</p><p><strong>a pool of temporary compute that your application knows how to use.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*DhxnzjJWPtdWoWaxwpsYMA.png" /><figcaption>Workflow diagram</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06adee8c888d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When LLMs Meet GIS: Building a Natural-Language Geospatial Query System with LLMs, FastAPI…]]></title>
            <link>https://medium.com/@sraza0098/when-llms-meet-gis-building-a-natural-language-geospatial-query-system-with-llms-fastapi-67a7279a6566?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/67a7279a6566</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 18:21:32 GMT</pubDate>
            <atom:updated>2026-08-10T18:21:32.691Z</atom:updated>
            <content:encoded><![CDATA[<h3>When LLMs Meet GIS: Building a Natural-Language Geospatial Query System with LLMs, FastAPI, PostGIS, Geo Server and Understanding Where Embeddings and RAG Actually Belong</h3><p>Imagine opening a map and typing:</p><blockquote><em>Show me </em><strong><em>high </em></strong><em>and </em><strong><em>critical </em></strong><em>incidents within 5 km of Manchester.</em></blockquote><p>No dropdowns. No SQL. No GIS expertise required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45ionQDCIIqYGg24xy0-PQ.png" /><figcaption>Application</figcaption></figure><p>The user asks a question in plain English, and a few seconds later the matching incidents appear on the map.</p><p>At first, this sounds like a straightforward LLM use case: send the question to an AI model, ask it to generate SQL, run that SQL against PostGIS, and return the result.</p><p>But there is a problem.</p><p>Do we really want an LLM deciding what SQL gets executed against our database?</p><p>That question shaped the architecture of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KNg33AMSPhHiUM6JgFm8g.png" /><figcaption>Architecture</figcaption></figure><h3>Let the LLM Understand the Human — Not Control the Database</h3><p>Instead of asking the model to generate SQL, the application asks it to translate natural language into a <strong>restricted query plan</strong>.</p><p>For example:</p><blockquote><em>Show me high and critical incidents within 5 km of Manchester.</em></blockquote><p>becomes:</p><pre>{<br>  &quot;operation&quot;: &quot;search_incidents&quot;,<br>  &quot;filters&quot;: {<br>    &quot;severities&quot;: [&quot;high&quot;, &quot;critical&quot;],<br>    &quot;place_name&quot;: &quot;Manchester&quot;,<br>    &quot;radius_metres&quot;: 5000<br>  }<br>}</pre><p>The LLM is responsible for understanding:</p><ul><li>“show me” means a search;</li><li>“high and critical” are severity filters;</li><li>“5 km” means 5000 metres;</li><li>Manchester is a location.</li></ul><p>But it never writes or executes SQL.</p><p>That responsibility remains with FastAPI.</p><p>The architecture is therefore:</p><pre>User<br>  ↓<br>React<br>  ↓<br>FastAPI<br>  ↓<br>LLM<br>  ↓<br>Structured Query Plan<br>  ↓<br>Validation<br>  ↓<br>Parameterised SQL<br>  ↓<br>PostGIS<br>  ↓<br>GeoJSON<br>  ↓<br>Map</pre><p>The principle is simple:</p><blockquote><strong><em>The AI decides what the user means. The application decides how to execute it.</em></strong></blockquote><h3>Prompt vs Schema</h3><p>Two things help keep the LLM under control: the <strong>prompt</strong> and the <strong>schema</strong>.</p><p>The prompt describes how the model should behave.</p><p>For example:</p><pre>Supported severities:<br>low, medium, high, critical.</pre><pre>Do not invent coordinates.</pre><pre>Ask for clarification when a spatial request<br>does not provide enough information.</pre><pre>Reject requests outside incident querying.</pre><p>The schema controls what the model is actually allowed to return.</p><p>At the highest level, the response might only be:</p><pre>query<br>clarification<br>unsupported</pre><p>So if someone asks:</p><blockquote><em>Show incidents near Manchester.</em></blockquote><p>the model should not invent what “near” means.</p><p>It can instead return:</p><pre>{<br>  &quot;kind&quot;: &quot;clarification&quot;,<br>  &quot;message&quot;: &quot;What radius should I use around Manchester?&quot;<br>}</pre><p>And if someone asks:</p><blockquote><em>Write me a poem.</em></blockquote><p>the result can simply be:</p><pre>{<br>  &quot;kind&quot;: &quot;unsupported&quot;<br>}</pre><p>Only a valid query reaches PostGIS.</p><h3>But What If Manchester Isn’t in the Database?</h3><p>This is where GIS becomes interesting.</p><p>An incident table does not necessarily need a city_name column.</p><p>It could contain only:</p><pre>id<br>severity<br>status<br>geometry</pre><p>with locations stored as PostGIS points.</p><p>If the user asks:</p><blockquote><em>Show high incidents within 5 km of Manchester.</em></blockquote><p>the backend can resolve Manchester using a geocoder:</p><pre>Manchester<br>    ↓<br>Geocoder<br>    ↓<br>Longitude + Latitude</pre><p>Then PostGIS performs the real geographic operation:</p><pre>Manchester coordinates<br>        +<br>5 km radius<br>        +<br>incident geometries<br>        ↓<br>ST_DWithin(...)</pre><p>The LLM understands the language.</p><p>The geocoder understands the place name.</p><p>PostGIS calculates the geography.</p><p>Each component has one clear responsibility.</p><h3>What If the User Draws a Polygon?</h3><p>Now imagine adding a drawing tool to the React/OpenLayers map.</p><p>The user draws an arbitrary polygon and asks:</p><blockquote><em>Show critical fires inside this area.</em></blockquote><p>Should the polygon coordinates go to the LLM?</p><p>Not really.</p><p>React already knows exactly what the polygon is.</p><p>So we can combine two sources of information:</p><pre>LLM:<br>severity = critical<br>type = fire</pre><pre>React:<br>drawn polygon</pre><p>FastAPI combines them and PostGIS performs:</p><pre>ST_Within(incident.geom, drawn_polygon)</pre><p>This is an important lesson when building AI applications:</p><blockquote><strong><em>Don’t send something to AI if your application already knows it precisely.</em></strong></blockquote><p>AI should solve ambiguity, not replace deterministic software.</p><h3>Where Does GeoServer Fit?</h3><p>GeoServer serves a different purpose.</p><p>The normal map layer can follow:</p><pre>PostGIS<br>   ↓<br>GeoServer<br>   ↓<br>WMS<br>   ↓<br>OpenLayers</pre><p>But natural-language analytical queries take another route:</p><pre>React<br>   ↓<br>FastAPI<br>   ↓<br>LLM<br>   ↓<br>PostGIS</pre><p>FastAPI connects directly to PostGIS using a restricted, read-only database account.</p><p>This gives the backend full control over validation, limits, spatial operations and parameterised SQL.</p><p>So:</p><blockquote><strong><em>GeoServer publishes the map. FastAPI performs application queries.</em></strong></blockquote><h3>Where Embeddings Become Interesting</h3><p>At this point the application doesn’t actually need embeddings.</p><p>If a user asks:</p><blockquote><em>Show critical incidents.</em></blockquote><p>normal SQL works perfectly.</p><p>If they ask:</p><blockquote><em>Show incidents within 5 km of Manchester.</em></blockquote><p>PostGIS works perfectly.</p><p>But imagine every incident also contains a free-text description:</p><blockquote><em>A lorry overturned on the motorway, blocking two lanes and causing heavy congestion.</em></blockquote><p>Now the user asks:</p><blockquote><em>Show incidents involving road obstruction.</em></blockquote><p>The exact words road obstruction might never appear in the database.</p><p>A traditional text search could miss the incident.</p><p>Embeddings can understand that:</p><pre>road obstruction</pre><pre>is semantically similar to</pre><pre>blocking two motorway lanes</pre><p>The incident description can be converted into an embedding and stored, for example using pgvector:</p><pre>incident<br>--------------------------------<br>id<br>severity<br>description<br>description_embedding<br>geom</pre><p>Then a query such as:</p><blockquote><em>Show high incidents involving blocked roads within 5 km of Manchester.</em></blockquote><p>can combine three different techniques:</p><pre>high<br>→ normal SQL</pre><pre>blocked roads<br>→ embedding similarity</pre><pre>within 5 km of Manchester<br>→ PostGIS</pre><p>That is where semantic search becomes genuinely useful.</p><h3>And Where Does RAG Fit?</h3><p>Embeddings can also be used for something completely different: <strong>giving the LLM domain knowledge</strong>.</p><p>Imagine the organisation has a policy document saying:</p><blockquote><em>A serious incident is defined as High or Critical severity.</em></blockquote><p>Now a user asks:</p><blockquote><em>Show serious incidents.</em></blockquote><p>Should the model simply guess what “serious” means?</p><p>No.</p><p>Instead, the policy documents can be split into chunks, converted into embeddings and stored in a vector database.</p><p>When the user asks about “serious incidents”, the application retrieves the relevant policy passage first:</p><pre>User question<br>      ↓<br>Embedding search<br>      ↓<br>Relevant policy:<br>&quot;Serious means High or Critical.&quot;<br>      ↓<br>LLM<br>      ↓<br>Query Plan</pre><p>Now the model is working with actual organisational knowledge instead of guessing.</p><p>That is <strong>Retrieval-Augmented Generation — RAG</strong>.</p><p>The distinction is simple:</p><blockquote><strong><em>Semantic search retrieves the data the user wants.</em></strong></blockquote><blockquote><strong><em>RAG retrieves knowledge that helps the LLM understand what the user wants.</em></strong></blockquote><h3>Putting It All Together</h3><p>A more advanced version of the architecture could eventually look like:</p><pre>User<br>                          |<br>                          v<br>                     React / Map<br>                          |<br>                          v<br>                       FastAPI<br>                          |<br>              +-----------+-----------+<br>              |                       |<br>              v                       v<br>        Policy retrieval          LLM<br>           (RAG)                    |<br>              |                     |<br>              +----------+----------+<br>                         |<br>                    Query Plan<br>                         |<br>          +--------------+--------------+<br>          |                             |<br>          v                             v<br>       PostGIS                       pgvector<br>   spatial + filters            semantic similarity<br>          |                             |<br>          +--------------+--------------+<br>                         |<br>                         v<br>                       Result<br>                         |<br>                         v<br>                       GeoJSON<br>                         |<br>                         v<br>                  OpenLayers Map</pre><p>What started as:</p><blockquote><em>“Can I let users query a map using English?”</em></blockquote><p>quickly became a much more interesting architectural question:</p><blockquote><strong><em>Which parts should actually be intelligent, and which parts should remain deterministic?</em></strong></blockquote><p>For me, the answer became clear.</p><p>The LLM is excellent at understanding language.</p><p>FastAPI is excellent at enforcing application rules.</p><p>PostGIS is excellent at geography.</p><p>GeoServer is excellent at publishing GIS data.</p><p>Embeddings are excellent at finding semantic similarity.</p><p>RAG is excellent at bringing private domain knowledge into the LLM’s context.</p><p>The best architecture is not the one where AI does everything.</p><p>It is the one where AI does <strong>exactly the part where intelligence adds value</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94SkqJLQ5vgMCJpOe53pqA.png" /><figcaption>Use case</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67a7279a6566" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Maps to Meaning: Solving Geospatial Data Discovery with Microsoft Foundry, Embeddings and…]]></title>
            <link>https://medium.com/@sraza0098/from-maps-to-meaning-solving-geospatial-data-discovery-with-microsoft-foundry-embeddings-and-b335ab2752fe?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b335ab2752fe</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 20:35:28 GMT</pubDate>
            <atom:updated>2026-07-23T20:35:28.224Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Maps to Meaning: Solving Geospatial Data Discovery with Microsoft Foundry, Embeddings and Vector Search</h3><h3>How embeddings, vector search and Microsoft Foundry can turn a confusing geospatial catalogue into a useful decision-support tool</h3><p>Heavy rain has been falling for hours.</p><p>An emergency-planning officer needs to identify communities that may become isolated if nearby roads flood. The organisation already owns hundreds of geospatial datasets:</p><ul><li>flood-risk zones,</li><li>river networks,</li><li>road closures,</li><li>terrain models,</li><li>drainage infrastructure,</li><li>historical incidents,</li><li>administrative boundaries,</li><li>and satellite imagery.</li></ul><p>The problem is not a lack of data.</p><p>The problem is finding the right data quickly.</p><p>The officer searches the catalogue for:</p><blockquote><em>Roads and villages likely to become inaccessible during heavy rainfall.</em></blockquote><p>A traditional search may look only for matching words. It might miss a dataset called:</p><blockquote><em>Surface Water Susceptibility Areas</em></blockquote><p>or:</p><blockquote><em>Transport Network Low-Point Analysis</em></blockquote><p>Neither title contains “inaccessible villages”, but both may be highly relevant.</p><p>This is where embeddings and vector search become genuinely useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16r9qn3YI1mvx0AxGfsY3A.png" /><figcaption>Architecture Diagram</figcaption></figure><h3>Search by meaning, not just matching words</h3><p>An embedding converts text into a numerical representation of its meaning.</p><p>Conceptually:</p><pre>“Villages cut off by flooded roads”<br>                 ↓<br>[0.018, -0.072, 0.119, 0.044, ...]</pre><p>A geospatial dataset description is converted in the same way:</p><pre>“Road sections susceptible to surface-water disruption”<br>                 ↓<br>[0.021, -0.069, 0.113, 0.049, ...]</pre><p>The wording is different, but the meaning is similar.</p><p>Because the vectors sit close together, the system can recognise that the dataset may help answer the officer’s question.</p><p>That gives us semantic search:</p><blockquote><em>Find geospatial information that is conceptually relevant, even when the terminology is different.</em></blockquote><h3>Preparing the geospatial catalogue</h3><p>Before anyone performs a search, the system prepares the catalogue.</p><p>For each dataset, we combine useful metadata such as:</p><pre>Title:<br>Surface Water Susceptibility Areas</pre><pre>Summary:<br>Areas that may experience flooding following intense rainfall.</pre><pre>Data type:<br>Polygon</pre><pre>Geographic coverage:<br>England</pre><pre>Themes:<br>Flooding, drainage, emergency planning</pre><pre>Update frequency:<br>Quarterly</pre><p>That text is sent to an embedding model through Microsoft Foundry.</p><p>The returned vector is stored in a vector index, while the original metadata is kept separately.</p><p>In simple pseudocode:</p><pre>FOR every geospatial dataset:</pre><pre>    collect its title, summary and themes</pre><pre>    turn that text into an embedding</pre><pre>    add the embedding to the vector index</pre><pre>    save the dataset metadata alongside its ID</pre><p>A slightly more technical version looks like this:</p><pre>for dataset in catalogue:<br>    searchable_text = combine(<br>        dataset.title,<br>        dataset.summary,<br>        dataset.themes,<br>        dataset.data_type,<br>        dataset.geographic_coverage,<br>    )</pre><pre>    vector = embedding_model.embed(searchable_text)</pre><pre>    vector_index.add(<br>        dataset_id=dataset.id,<br>        vector=vector,<br>    )</pre><pre>    metadata[dataset.id] = dataset</pre><p>The important point is that this work happens before the user searches.</p><p>The API loads the completed index and uses it for fast lookups.</p><h3>Why use a vector index?</h3><p>A catalogue may contain thousands — or millions — of vectors.</p><p>Comparing every user query against every stored vector would eventually become slow and expensive.</p><p>A vector index solves a different question:</p><blockquote><em>Which stored vectors are closest to this query?</em></blockquote><p>For a largely static catalogue, a lightweight approximate nearest-neighbour index can work well. Larger or frequently changing catalogues may use a managed vector-search service.</p><p>The technology can vary, but the architecture remains the same:</p><pre>Geospatial metadata<br>        ↓<br>Embeddings<br>        ↓<br>Vector index<br>        ↓<br>Fast similarity search</pre><h3>What happens when the user searches?</h3><p>The emergency officer enters:</p><blockquote><em>Find roads and settlements that may become isolated during intense rainfall.</em></blockquote><p>The application combines the request into one searchable text block and sends it to the same embedding model used to build the catalogue index.</p><p>That detail matters.</p><p>The catalogue and the user query must use compatible embeddings. Otherwise, their vectors cannot be meaningfully compared.</p><p>The vector index then retrieves a shortlist such as:</p><ol><li>Surface Water Susceptibility Areas</li><li>Road Network Low Points</li><li>Historical Flooded Roads</li><li>Settlement Boundaries</li><li>Digital Terrain Model</li><li>River Levels and Gauging Stations</li></ol><p>These are candidates, not final answers.</p><p>Vector similarity can find semantically related datasets, but it does not fully understand the operational task.</p><p>For example:</p><ul><li>a terrain model may be useful but difficult to use directly;</li><li>settlement boundaries are necessary but do not indicate flood risk;</li><li>historical flood records may be highly relevant but outdated;</li><li>river gauges may not help with surface-water flooding.</li></ul><p>That is where the language model becomes useful.</p><h3>The LLM should judge the shortlist — not search everything</h3><p>The retrieved candidates are sent to a language model deployed through Microsoft Foundry.</p><p>The prompt might say:</p><pre>The user wants to identify settlements that may become inaccessible<br>when roads flood during intense rainfall.</pre><pre>Evaluate the following geospatial datasets.</pre><pre>For each dataset:<br>- explain how it could help;<br>- score its relevance;<br>- identify important limitations;<br>- state whether it is directly usable or requires combination with other data.</pre><pre>Then recommend the best group of datasets for the task.</pre><pre>Return structured JSON.</pre><p>The LLM is not asked to invent datasets.</p><p>It is not asked to search the whole catalogue.</p><p>It receives a controlled shortlist produced by vector retrieval and then adds reasoning.</p><p>This separation is important:</p><pre>Embeddings understand similarity.</pre><pre>Vector search retrieves candidates.</pre><pre>The LLM evaluates usefulness.</pre><pre>The API coordinates the process.</pre><h3>Why group evaluation matters</h3><p>A dataset can be useful individually but insufficient on its own.</p><p>For this flood-accessibility problem, the system might recommend:</p><ul><li>flood susceptibility polygons,</li><li>the road network,</li><li>settlement boundaries,</li><li>and a terrain model.</li></ul><p>Each dataset plays a different role.</p><p>The best result is not necessarily the four highest individual similarity scores. Four similar flood layers may be repetitive while still missing the road and settlement information needed to answer the real question.</p><p>The system therefore evaluates both:</p><h3>Individual relevance</h3><pre>How useful is this dataset by itself?</pre><h3>Group usefulness</h3><pre>Do these datasets work together to solve the task?<br>Are important data types missing?<br>Are several recommendations effectively duplicates?</pre><p>That distinction turns search results into a more practical geospatial workflow.</p><h3>Returning structured results</h3><p>The model should not return an uncontrolled paragraph that the application must interpret.</p><p>Instead, it returns a structure such as:</p><pre>{<br>  &quot;recommendedDatasets&quot;: [<br>    {<br>      &quot;title&quot;: &quot;Surface Water Susceptibility Areas&quot;,<br>      &quot;relevance&quot;: 0.94,<br>      &quot;role&quot;: &quot;Identifies locations exposed to rainfall-driven flooding&quot;<br>    },<br>    {<br>      &quot;title&quot;: &quot;Road Network Low Points&quot;,<br>      &quot;relevance&quot;: 0.91,<br>      &quot;role&quot;: &quot;Identifies road sections where water may accumulate&quot;<br>    },<br>    {<br>      &quot;title&quot;: &quot;Settlement Boundaries&quot;,<br>      &quot;relevance&quot;: 0.76,<br>      &quot;role&quot;: &quot;Connects affected roads to nearby communities&quot;<br>    }<br>  ],<br>  &quot;groupEvaluation&quot;: {<br>    &quot;coverage&quot;: 0.89,<br>    &quot;redundancy&quot;: 0.08,<br>    &quot;overall&quot;: 0.91<br>  }<br>}</pre><p>The API validates this response before sending it to the user interface.</p><p>That gives the frontend a predictable contract rather than a block of prose.</p><h3>Why processing happens in the background</h3><p>Generating embeddings, searching the index and running several evaluations may take time.</p><p>Instead of keeping one HTTP request open, the API can respond immediately:</p><pre>POST /geospatial-analysis<br>        ↓<br>202 Accepted<br>        ↓<br>Request ID returned</pre><p>The user interface then checks the result endpoint:</p><pre>GET /geospatial-analysis/{request-id}</pre><p>The status may move through:</p><pre>accepted → partial → complete</pre><p>This also allows successful results to survive if one evaluation temporarily fails.</p><p>For example, dataset retrieval may complete even if the group explanation is still being generated.</p><h3>The full workflow</h3><p>For non-developers, the whole system can be understood like this:</p><pre>A user describes a real-world geospatial problem<br>                    ↓<br>The description is converted into an embedding<br>                    ↓<br>The vector index finds semantically related datasets<br>                    ↓<br>The LLM evaluates whether those datasets are genuinely useful<br>                    ↓<br>The API returns ranked, explained and structured recommendations</pre><p>And in pseudocode:</p><pre>RECEIVE the user’s geospatial question</pre><pre>CONVERT the question into an embedding</pre><pre>SEARCH the vector index</pre><pre>RETRIEVE the most similar datasets</pre><pre>ASK the language model:<br>    Which datasets are actually useful?<br>    What role does each one play?<br>    What is missing?<br>    Do the datasets work well together?</pre><pre>VALIDATE the answer</pre><pre>RETURN a structured result</pre><h3>What made the architecture work</h3><p>The strongest design decision was not choosing a particular model.</p><p>It was giving each component one clear responsibility:</p><pre>Microsoft Foundry<br>    provides the embedding and language models</pre><pre>Embedding model<br>    represents semantic meaning</pre><pre>Vector index<br>    retrieves likely datasets quickly</pre><pre>Language model<br>    evaluates and explains the shortlist</pre><pre>API<br>    manages processing, caching and failures</pre><pre>Frontend<br>    presents the result without recalculating it</pre><p>That separation makes the system easier to test and trust.</p><p>When a recommendation looks wrong, we can investigate whether the issue came from:</p><ul><li>poor metadata,</li><li>an unsuitable embedding,</li><li>weak retrieval,</li><li>a prompt problem,</li><li>invalid model output,</li><li>or incorrect presentation.</li></ul><h3>The bigger lesson</h3><p>Geospatial organisations rarely suffer from having no data.</p><p>They suffer from having large catalogues that are difficult to navigate, inconsistent terminology and limited time to understand which datasets work together.</p><p>Embeddings do not replace geospatial expertise.</p><p>Language models do not replace spatial analysis.</p><p>But together, they can reduce the time between:</p><blockquote><em>We have thousands of maps.</em></blockquote><p>and:</p><blockquote><em>These are the datasets we need to investigate the problem.</em></blockquote><p>That is where this architecture becomes valuable.</p><p>Not because AI magically understands every map — but because the system helps people find the right geospatial evidence before the decision becomes urgent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TH8Dcl-dJfzWLJXK8D9yNw.png" /><figcaption>Use cases</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b335ab2752fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Raw Sentinel-2 to AI-Ready Tensors: How We Built a Parallel Geospatial Pipeline That Actually…]]></title>
            <link>https://medium.com/@sraza0098/from-raw-sentinel-2-to-ai-ready-tensors-how-we-built-a-parallel-geospatial-pipeline-that-actually-7bec7a8a3a6d?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bec7a8a3a6d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[earth-observation]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 20:39:19 GMT</pubDate>
            <atom:updated>2026-07-15T08:21:35.857Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Raw Sentinel-2 to AI-Ready Tensors: How We Built a Parallel Geospatial Pipeline That Actually Scales</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynMq9fzZ5CUksDsYmNTzBw.png" /></figure><p>Everyone likes to talk about AI models.</p><p>In geospatial projects, the exciting part is usually the same: land-cover classification, crop monitoring, flood mapping, change detection, environmental forecasting, and all the interesting things machine learning can do once the data is ready.</p><p>But in our project, the hardest part was not the model.</p><p>It was building the pipeline that turns years of raw Sentinel-2 imagery into something a model can actually use at scale.</p><p>That sounds like a preprocessing problem. In reality, it became a distributed systems problem, a cloud cost problem, an orchestration problem, and a data-engineering problem all at once.</p><p>We were building a large-scale Earth observation pipeline that could take Sentinel-2 scenes, filter them, downscale them into fixed-size tensors such as 128×128, and export them in formats that downstream AI workflows can consume efficiently, especially:</p><ul><li><strong>time-series Zarr outputs</strong> for structured analysis and experimentation</li><li><strong>TFRecords</strong> for machine learning training pipelines</li></ul><p>The goal was simple to describe: take messy satellite archives and turn them into clean, model-ready data.</p><p>The hard part was making that reliable, fast, and safe across more than <strong>56,000</strong> tiles.</p><h3>Why this matters in the real GIS world</h3><p>A lot of GIS work still loses time in the same place: data preparation.</p><p>A data scientist or geospatial analyst might want to answer questions like:</p><ul><li>How is vegetation changing over time?</li><li>Where are crops under stress?</li><li>Which areas are flooding more frequently?</li><li>Where is land use changing fastest?</li><li>Which regions should be inspected first by a human analyst?</li><li>How can we feed satellite time series into an ML model without hand-building every tensor?</li></ul><p>The model can help with those questions, but only if the input data is consistent.</p><p>Raw Sentinel-2 archives are not naturally ready for AI. They come as large rasters, variable time series, changing scene quality, and a lot of metadata. If every analyst has to rediscover scenes, filter them, resample them, and build model tensors manually, the same work gets repeated again and again.</p><p>That is what this project tried to solve.</p><p>The value of the pipeline is that it gives GIS and AI teams a reusable preprocessing layer. Instead of spending days turning raw imagery into training data, they can start with standardised outputs that are already shaped for analysis or model training.</p><p>That means:</p><ul><li>faster experimentation,</li><li>more reproducible datasets,</li><li>less repeated preprocessing work,</li><li>and a much shorter path from archive to model.</li></ul><h3>What we were actually building</h3><p>At a high level, our workflow looked like this:</p><ol><li>discover Sentinel-2 scenes for a tile and date range</li><li>filter out scenes with no useful coverage</li><li>read the required raster bands</li><li>downscale them into a fixed output size</li><li>assemble them into a time series</li><li>write the result as either Zarr or TFRecord</li><li>store the final output in S3</li></ol><p>This is the part many people underestimate.</p><p>Machine learning models do not want “whatever the satellite archive gives you.” They want a consistent tensor. For example, if you are training a temporal model, you want a predictable sample structure: same spatial size, same band ordering, same metadata assumptions, same filtering logic.</p><p>That is where TFRecords become especially useful.</p><h3>Why TFRecords were important</h3><p>In this project, TFRecords were not just an output format for the sake of it. They were the bridge between geospatial processing and model training.</p><p>Once imagery has been filtered, downscaled, and packed into TFRecords, it becomes much easier to feed into AI pipelines. That helps with:</p><ul><li>building training datasets for temporal models</li><li>creating batches efficiently</li><li>reducing repeated file-open overhead during training</li><li>making model pipelines simpler and more consistent</li><li>supporting scalable ML workflows where the same data is read again and again</li></ul><p>So in practical terms, the pipeline was doing this:</p><p><strong>raw Sentinel-2 archive → AI-ready training examples</strong></p><p>That is a huge shift in usability.</p><p>Instead of data scientists spending their time on raster wrangling, they can spend it on experiments, evaluation, and model design.</p><h3>Why we also cared about Zarr</h3><p>At the same time, we did not want to lock everything into one training format.</p><p>That is why time-series Zarr-style outputs also mattered.</p><p>Zarr is especially useful when you want to inspect, slice, analyse, and experiment with structured arrays before committing to a full training workflow. It is a very natural format for geospatial tensor exploration.</p><p>So the project was really serving two audiences at once:</p><ul><li>the <strong>data scientist</strong> who wants model-friendly TFRecords</li><li>the <strong>analyst or researcher</strong> who wants structured time-series arrays for inspection and experimentation</li></ul><p>That flexibility was one of the strengths of the system.</p><h3>The first scaling problem: the worker model</h3><p>Our earlier worker design used a claims-based approach in S3.</p><p>Workers would check shared state, create claim files, process tiles, and write status files. It worked, but it was not ideal once we started thinking seriously about scale.</p><p>The problems were familiar:</p><ul><li>stale claim files could remain behind</li><li>old in_progress records needed cleanup</li><li>worker coordination depended too much on shared S3 state</li><li>scaling many workers felt clumsy</li></ul><p>So we moved toward an <strong>SQS-based model</strong>.</p><p>Instead of coordinating through claim objects, the workflow became:</p><ul><li>enqueue tile jobs into SQS</li><li>let workers pull tasks from the queue</li><li>use visibility timeout while work is running</li><li>delete the message only after successful completion</li></ul><p>That gave us a cleaner control plane. It did not automatically make a tile faster, but it made the worker fleet much easier to reason about.</p><p>And that matters a lot when scaling.</p><h3>The second scaling problem: parallelism is useless if the instance is wrong</h3><p>One of the most useful lessons from this project was learning that “more parallelism” does not automatically mean “more throughput.”</p><p>We tested different EC2 shapes because we did not want to guess.</p><p>A smaller instance such as <strong>m6g.2xlarge</strong> could run the pipeline, but once concurrency increased, it started to show clear limits. Some runs started fast and then degraded as work continued.</p><p>That was an important clue.</p><p>The bottleneck was not just orchestration. It was the full data path:</p><p><strong>S3 → EC2 → RAM → CPU → output → S3</strong></p><p>If the instance cannot sustain the right read throughput under concurrency, then more workers or more threads simply hit the ceiling faster.</p><p>This is why instance benchmarking became part of the engineering work, not an afterthought.</p><p>We moved toward stronger, more network-oriented workers, and in the Terraform rollout path, <strong>c6gn.4xlarge</strong> became the meaningful production-style baseline direction because it behaved much better under the workload than the weaker instance did.</p><p>That choice mattered because the pipeline is heavily I/O-driven. The wrong instance can make good code look bad.</p><h3>The third scaling problem: data locality and AWS region</h3><p>Another important design choice was placing compute in the <strong>same AWS region as the source data buckets</strong>.</p><p>This may sound like an infrastructure detail, but at scale it is absolutely part of the data-engineering strategy.</p><p>When you are repeatedly reading large Earth observation assets from S3, region placement affects:</p><ul><li>transfer latency</li><li>throughput consistency</li><li>operational simplicity</li><li>and cost</li></ul><p>Keeping the EC2 workers in the same region as the data helps avoid unnecessary cross-region movement and reduces the chance of paying extra just to move data farther than needed inside AWS.</p><p>For satellite workloads, where the pipeline can read very large volumes of imagery, this matters a lot.</p><p>This is one of those practical design decisions that can make a project far more economical and predictable.</p><h3>Parallel processing was essential</h3><p>This was never a single-threaded script.</p><p>The pipeline used parallelism in multiple places:</p><ul><li>metadata and filtering work</li><li>scene-level raster processing</li><li>download threads</li><li>upload concurrency</li><li>worker fleets across multiple EC2 instances</li></ul><p>A simplified pattern from the processing side looked like this:</p><pre>with ProcessPoolExecutor(max_workers=cfg.scene_workers) as ex:<br>    for rr in ex.map(_process_scene_star, args_iter, chunksize=4):<br>        if rr.ok and rr.cube is not None:<br>            cube_store[rr.index] = rr.cube<br>            good_mask[rr.index] = True</pre><p>This was essential for good throughput, but it only really worked once the surrounding system was tuned properly:</p><ul><li>the right instance type,</li><li>the right read strategy,</li><li>earlier filtering,</li><li>and the right worker orchestration model.</li></ul><p>Parallelism was necessary. It was not sufficient by itself.</p><h3>Filtering saved more money than we expected</h3><p>Another lesson was that filtering matters far more than people expect.</p><p>If a tile has no useful scenes, or no meaningful coverage, the worst time to discover that is after you have already paid to read and decode the rasters.</p><p>So we pushed filtering earlier using metadata-driven checks, especially around L1C scene coverage. That let us avoid wasting compute on scenes that were never going to produce useful output.</p><p>At scale, this is not a small optimisation. It directly affects how much useful work the system actually does.</p><h3>The safety challenge: do not repeat historical work</h3><p>Once we moved to SQS, we had another serious requirement:</p><p><strong>do not reprocess work that has already been completed or historically known to be empty.</strong></p><p>This turned out to be more subtle than expected.</p><p>We had historical state in S3 that included:</p><ul><li>outputs already written</li><li>tiles explicitly marked as no_data</li><li>older failures that were really “no data” cases in disguise</li><li>stale in_progress records that needed cleanup</li></ul><p>So the new enqueue and worker logic had to be taught how to understand that history.</p><p>We ended up adding protection in both the enqueue script and the worker itself to skip:</p><ul><li>tiles whose final output already exists</li><li>tiles already marked no_data</li><li>legacy failure records whose logs clearly showed there were no L1C STAC items for that tile and date range</li></ul><p>That was one of the most important engineering steps in the migration, because scaling the wrong work is worse than not scaling at all.</p><h3>The dry run that proved the migration was safe</h3><p>Before sending real messages to the queue, we used dry runs heavily.</p><p>That gave us a safe way to verify what the new system would do without actually triggering processing.</p><p>The final validated dry-run result showed:</p><ul><li>total inventory: <strong>56,686</strong></li><li>skipped existing output: <strong>5,326</strong></li><li>skipped explicit no_data: <strong>940</strong></li><li>skipped legacy no-L1C historical failures: <strong>8,050</strong></li><li>true candidates left to process: <strong>42,370</strong></li></ul><p>That was the point where we knew the new SQS path was not going to blindly repeat historical work.</p><h3>Where Terraform helped</h3><p>Terraform was a major part of making this practical.</p><p>It gave us:</p><ul><li><strong>Launch Templates</strong> for consistent workers</li><li><strong>Auto Scaling Groups</strong> for fleet management</li><li>safe rollout from zero workers upward</li><li>repeatable infrastructure changes</li><li>easier worker replacement and scaling</li></ul><p>This mattered because our workers were never meant to be handcrafted machines. They were meant to be a fleet.</p><p>Terraform let us treat them that way.</p><p>It also made the migration safer. We could keep desired capacity at zero while validating queue logic, then only scale up once the dry runs and skip protections were correct.</p><p>That kind of rollout discipline is easy to underestimate until you really need it.</p><h3>What we got from the project</h3><p>By the end, we had something much more valuable than just a preprocessing script.</p><p>We had a parallel, cloud-native pipeline that could:</p><ul><li>turn raw Sentinel-2 archives into model-ready tensors</li><li>support both structured analysis and training workflows</li><li>scale through worker fleets rather than handcrafted servers</li><li>use cloud-native orchestration instead of brittle shared claim state</li><li>avoid repeating already-completed or historically-empty work</li><li>keep compute close to data for better cost and performance</li></ul><p>For GIS and AI teams, that solves a very real daily problem:</p><p><strong>it removes the repeated pain of preparing raw Earth observation data every single time a new modelling task begins.</strong></p><p>Instead of rebuilding preprocessing logic in every notebook, every prototype, and every training job, teams can start from stable, reusable outputs.</p><p>And that is what makes large-scale geospatial AI practical.</p><p>Because before you can scale the model, you have to scale the data pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEaNB0UTgbyUg4_m2wtlxQ.png" /><figcaption>Sentinel 2 Processing System</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bec7a8a3a6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js Data Fetching Made Simple]]></title>
            <link>https://medium.com/@sraza0098/next-js-data-fetching-made-simple-40588deaab2e?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/40588deaab2e</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 21:41:08 GMT</pubDate>
            <atom:updated>2026-07-01T21:41:08.482Z</atom:updated>
            <content:encoded><![CDATA[<p>When you first start working with Next.js, one thing can feel confusing very quickly:</p><blockquote><em>Where should I fetch my data?</em></blockquote><p><em>Should the browser call the API directly?</em></p><p><em>Should the Next.js server call the API?</em></p><p><em>What is an API proxy route?</em></p><p><em>Where does React Query fit in?</em></p><p><em>And if Next.js already runs code on the server, why do people still create proxy routes?</em></p><p>These questions are very normal, especially if you are coming from a React background.</p><p>In React, the mental model is usually simple:</p><pre>Component loads<br>→ useEffect or event handler runs<br>→ fetch data from API<br>→ update state<br>→ render UI</pre><p>In Next.js, we get more options. That is powerful, but it also means we need to be more intentional.</p><p>This article explains the idea in simple terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*XNl5IE43LFisCCM-DjDNIQ.png" /><figcaption>Next JS + React JS</figcaption></figure><h3>React and Next.js are not the same thing</h3><p>React is a UI library.</p><p>It helps us build components.</p><p>Next.js is a framework built on top of React.</p><p>It gives us extra features like:</p><pre>Routing<br>Server-side rendering<br>Server components<br>API routes<br>Layouts<br>Middleware<br>Data fetching patterns</pre><p>So with plain React, most of the work usually happens in the browser.</p><p>With Next.js, some work can happen on the server before the page reaches the browser.</p><p>That is one of the biggest differences.</p><h3>A simple example</h3><p>Imagine we are building a small app called <strong>Movie Finder</strong>.</p><p>It has three pages:</p><pre>/                 Home page<br>/search           Search movies<br>/movies/[id]      Movie details page</pre><p>On the movie details page, we need to show:</p><pre>Movie title<br>Description<br>Rating<br>Cast<br>Recommended movies</pre><p>This data comes from a backend API.</p><p>Now we have a choice.</p><p>Should we fetch this data from the browser?</p><p>Or should we fetch it on the server?</p><h3>Option 1: Fetching from the browser</h3><p>In a client component, we might do something like this:</p><pre>&#39;use client&#39;;</pre><pre>import { useEffect, useState } from &#39;react&#39;;</pre><pre>export function MovieDetails({ movieId }: { movieId: string }) {<br>  const [movie, setMovie] = useState(null);</pre><pre>  useEffect(() =&gt; {<br>    fetch(`/api/movies/${movieId}`)<br>      .then((res) =&gt; res.json())<br>      .then(setMovie);<br>  }, [movieId]);</pre><pre>  if (!movie) {<br>    return &lt;p&gt;Loading...&lt;/p&gt;;<br>  }</pre><pre>  return &lt;h1&gt;{movie.title}&lt;/h1&gt;;<br>}</pre><p>This works.</p><p>But the browser has to:</p><pre>Download JavaScript<br>Run JavaScript<br>Make the API request<br>Wait for the response<br>Update the page</pre><p>That is fine for interactive parts of the app.</p><p>But for data that is needed immediately when the page loads, Next.js gives us a better option.</p><h3>Option 2: Fetching on the server</h3><p>In Next.js App Router, pages are server components by default.</p><p>That means you can do this:</p><pre>export default async function MoviePage({<br>  params,<br>}: {<br>  params: { id: string };<br>}) {<br>  const movie = await getMovie(params.id);</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;{movie.title}&lt;/h1&gt;<br>      &lt;p&gt;{movie.description}&lt;/p&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Here, getMovie() runs on the server.</p><p>The browser does not need to run this fetch logic.</p><p>The server gets the data, prepares the page, and sends the rendered result to the browser.</p><p>That gives us some nice advantages:</p><pre>The page can load with data already in place<br>Less JavaScript is sent to the browser<br>Backend URLs can stay hidden<br>Secrets and tokens stay on the server<br>The page is easier to share and refresh</pre><p>So far, this sounds simple.</p><p>But then another question appears.</p><h3>So why do we need API proxy routes?</h3><p>Let’s say our real backend API is here:</p><pre>https://internal-api.example.com/movies/123</pre><p>We may not want the browser to call this directly.</p><p>Why?</p><p>Because the real backend request may need:</p><pre>Private API base URL<br>Auth token<br>Basic auth credentials<br>Internal headers<br>Server-only environment variables</pre><p>Those things should not be exposed in browser code.</p><p>So instead of this:</p><pre>Browser → real backend API</pre><p>we use this:</p><pre>Browser → Next.js API proxy route → real backend API</pre><p>The browser calls a safe internal route:</p><pre>/api/proxy/movies/123</pre><p>Then the Next.js server calls the real backend API.</p><p>A simple way to think about it:</p><pre>The browser talks to your Next.js app.<br>Your Next.js app talks to the backend.</pre><p>The browser does not need to know where the real backend lives.</p><h3>What is an API proxy route?</h3><p>An API proxy route is just a small backend endpoint inside your Next.js app.</p><p>For example:</p><pre>/app/api/proxy/movies/[id]/route.ts</pre><p>The browser can call:</p><pre>/api/proxy/movies/123</pre><p>The route handler then calls:</p><pre>https://internal-api.example.com/movies/123</pre><p>So the proxy route acts like a middle layer.</p><p>It can handle:</p><pre>Auth headers<br>Backend URLs<br>Error handling<br>Request formatting<br>Response shaping<br>Logging<br>Server-only environment variables</pre><p>This keeps your UI code cleaner.</p><p>Your component does not need to know the real backend URL.</p><p>It just calls your own app.</p><h3>But if server components can fetch data, do we still need proxy routes?</h3><p>This is the important part.</p><p>Sometimes, no.</p><p>Sometimes, yes.</p><p>It depends where the request starts.</p><h3>Server component request</h3><p>If the request happens while rendering the page on the server, you can call your async function directly.</p><pre>Server component → async function → backend API</pre><p>Example:</p><pre>export default async function MoviePage({ params }) {<br>  const movie = await getMovie(params.id);</pre><pre>  return &lt;MovieDetails movie={movie} /&gt;;<br>}</pre><p>This is already server-side.</p><p>The browser is not making the request.</p><p>So you may not need to call your own proxy route here.</p><h3>Client component request</h3><p>But some requests happen after the page has loaded.</p><p>For example:</p><pre>User clicks “Show similar movies”<br>User submits a form<br>User expands a section<br>User selects an item<br>User refreshes part of the page<br>User checks job status</pre><p>These actions happen in the browser.</p><p>That means the request starts from a client component.</p><p>In that case, the browser should not call the real backend directly.</p><p>So we use the proxy route:</p><pre>Client component → API proxy route → backend API</pre><p>That is why both approaches can exist in the same app.</p><h3>The useful pattern</h3><p>A clean pattern is:</p><pre>1. Create a reusable async function<br>2. Use it directly from server components<br>3. Expose it through a proxy route for client components</pre><p>For example:</p><pre>getMovie(id)</pre><p>This function contains the real backend call.</p><p>A server page can use it directly:</p><pre>Movie page → getMovie(id)</pre><p>A proxy route can also use it:</p><pre>/api/proxy/movies/[id] → getMovie(id)</pre><p>So the actual backend logic lives in one place.</p><p>That is the main idea.</p><p>You are not duplicating the backend call everywhere.</p><p>You are giving yourself two safe ways to use it.</p><h3>Where React Query fits in</h3><p>React Query is another piece that can feel confusing at first.</p><p>React Query does not replace the proxy route.</p><p>React Query uses the proxy route.</p><p>The flow is:</p><pre>Client component<br>→ React Query hook<br>→ fetch(&#39;/api/proxy/...&#39;)<br>→ Next.js proxy route<br>→ backend API</pre><p>So why use React Query?</p><p>Because client-side requests need state.</p><p>Every request usually needs to handle:</p><pre>Loading<br>Error<br>Success<br>Retry<br>Caching<br>Refetching<br>Polling<br>Avoiding duplicate requests</pre><p>Without React Query, you may end up writing a lot of manual state:</p><pre>const [data, setData] = useState(null);<br>const [isLoading, setIsLoading] = useState(false);<br>const [error, setError] = useState(null);</pre><p>And then you need to remember to update all of it correctly.</p><p>React Query gives you that structure automatically.</p><p>Your component can simply say:</p><pre>const { data, isLoading, error } = useMovieQuery(movieId);</pre><p>That makes the component easier to read.</p><p>The component focuses on the UI.</p><p>The hook focuses on fetching data.</p><p>The proxy route focuses on talking safely to the backend.</p><h3>Think of the layers like this</h3><p>A helpful way to picture it:</p><pre>Component<br>  Shows the UI</pre><pre>React Query hook<br>  Manages client-side request state</pre><pre>Proxy route<br>  Protects backend access</pre><pre>Async function<br>  Contains the real backend call</pre><pre>Backend API<br>  Provides the actual data</pre><p>Each layer has a job.</p><p>That is better than putting everything inside one big component.</p><h3>A practical rule</h3><p>This rule helped me understand it:</p><pre>If the data is needed to render the page:<br>  Fetch it on the server.</pre><pre>If the data is needed after a user interaction:<br>  Fetch it from the client through a proxy route.</pre><pre>If the client request needs loading, error, caching, or polling:<br>  Wrap it in React Query.</pre><p>So:</p><pre>Initial page data:<br>  Server component → async function → backend API</pre><pre>Interactive client data:<br>  Client component → React Query hook → proxy route → async function → backend API</pre><h3>What about CORS?</h3><p>CORS is often mentioned when people talk about proxy routes.</p><p>CORS matters when browser JavaScript from one domain tries to call another domain.</p><p>For example:</p><pre>Frontend:<br>https://app.example.com</pre><pre>Backend:<br>https://api.example.net</pre><p>The browser may block the request unless the backend allows it.</p><p>Using a proxy can avoid this because the browser calls your own app:</p><pre>https://app.example.com/api/proxy/...</pre><p>Then your server calls the backend.</p><p>But CORS is not always the main reason for using a proxy.</p><p>In many real projects, the bigger reasons are:</p><pre>Hiding auth details<br>Keeping backend URLs out of the browser<br>Keeping API access consistent<br>Making code easier to test<br>Supporting both server and client components</pre><p>So proxy routes are not just a CORS workaround.</p><p>They are also an architecture choice.</p><h3>Is this over-engineering?</h3><p>Sometimes, yes.</p><p>For a tiny app, it may feel like too much.</p><p>You might wonder:</p><blockquote><em>Why not just fetch directly and finish the job?</em></blockquote><p>And honestly, for a small demo, that may be fine.</p><p>But in a real application, requirements change.</p><p>A request that starts server-side today may need to be triggered from the browser tomorrow.</p><p>A simple API call may later need authentication, error handling, caching, or polling.</p><p>A component that works today may become hard to test if all the fetch logic is inside it.</p><p>So a little structure early can save pain later.</p><h3>Final mental model</h3><p>Next.js gives us the ability to choose where code runs.</p><p>Some code belongs on the server.</p><p>Some code belongs in the browser.</p><p>Proxy routes help the browser safely reach backend services.</p><p>React Query helps client components manage API request state.</p><p>A clean setup often looks like this:</p><pre>Server page load:<br>  Server component<br>  → async function<br>  → backend API</pre><pre>Client interaction:<br>  Client component<br>  → React Query hook<br>  → API proxy route<br>  → async function<br>  → backend API</pre><p>Once this clicks, the whole data-fetching story in Next.js becomes much easier to understand.</p><p>The goal is not to add layers just to look clever.</p><p>The goal is to keep the app flexible, secure, testable, and easier to maintain as it grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40588deaab2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Unified Swagger UI for Multiple APIs with FastAPI]]></title>
            <link>https://medium.com/@sraza0098/building-a-unified-swagger-ui-for-multiple-apis-with-fastapi-63518e844986?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/63518e844986</guid>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 20:21:29 GMT</pubDate>
            <atom:updated>2025-06-27T20:21:29.268Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently worked on building a <strong>common Swagger documentation platform</strong> that brings together all our API docs into one place. I used the power of <strong>OpenAPI (Swagger)</strong>, which FastAPI conveniently supports out of the box.</p><p>You’ve probably seen many applications with OpenAPI already integrated — but I wanted to take it a step further. <strong>My goal was to combine all API endpoints across different services into one centralized service</strong> that could serve them through a single Swagger UI. This not only simplifies API management but also gives teams a clear, unified view of their entire system.</p><h3><strong>🧠 The Problem</strong></h3><p>In our microservices-based system, we had separate Swagger docs for each service — App A, App B, App C, and others. Jumping between them was inefficient. Users needed one place to browse and explore <strong>all endpoints</strong>, <strong>with grouping</strong>, and <strong>with authentication support</strong>.</p><p><strong>🛠️ Our Solution: A FastAPI Aggregator</strong></p><p>We built a lightweight FastAPI app that:</p><p>✅ Reads a configuration file listing each API<br> ✅ Fetches and merges their OpenAPI JSON specs<br> ✅ Rewrites paths with prefixes to avoid conflicts<br> ✅ Adds distinct tags per service for clarity<br> ✅ Hosts a single Swagger UI with everything neatly grouped</p><h3>📁 Configuration-Driven Setup</h3><p>We didn’t hardcode anything. Everything is configurable through a simple YAML file:</p><pre>title: &quot;Unified API Reference&quot;<br>version: &quot;1.0.0&quot;<br>openapi_version: &quot;3.1.0&quot;<br>docs_url: &quot;/docs&quot;<br>openapi_url: &quot;/openapi.json&quot;<br>sources:<br>  - name: &quot;App A&quot;<br>    prefix: &quot;/app-a&quot;<br>    url: &quot;https://api.example.com/app-a/openapi.json&quot;<br>  - name: &quot;App B&quot;<br>    prefix: &quot;/app-b&quot;<br>    url: &quot;https://api.example.com/app-b/openapi.json&quot;<br>  - name: &quot;App C&quot;<br>    prefix: &quot;/app-c&quot;<br>    url: &quot;https://api.example.com/app-c/openapi.json&quot;</pre><h3><strong>🧩 Core Logic: Merging the Specs</strong></h3><p>Here’s the important part — how we fetch and unify the specs:</p><pre>@dataclass<br>class APISource:<br>    name: str<br>    prefix: str<br>    url: str<br><br>@dataclass<br>class Config:<br>    title: str<br>    version: str<br>    openapi_version: str<br>    docs_url: str<br>    openapi_url: str<br>    sources: list[APISource]<br><br>def fetch_openapi_docs():<br>    merged_api = {<br>        &quot;openapi&quot;: config.openapi_version,<br>        &quot;info&quot;: {&quot;title&quot;: config.title, &quot;version&quot;: config.version},<br>        &quot;tags&quot;: [],<br>        &quot;paths&quot;: {},<br>        &quot;components&quot;: {&quot;schemas&quot;: {}},<br>    }<br><br>    for source in config.sources:<br>        response = requests.get(source.url)<br>        api_spec = response.json()<br><br>        merged_api[&quot;tags&quot;].append({&quot;name&quot;: source.name, &quot;description&quot;: f&quot;Endpoints from {source.name}&quot;})<br><br>        for path, methods in api_spec.get(&quot;paths&quot;, {}).items():<br>            new_path = f&quot;{source.prefix}{path}&quot;<br>            merged_api[&quot;paths&quot;][new_path] = {<br>                method: {**details, &quot;tags&quot;: [source.name]}<br>                for method, details in methods.items()<br>            }<br><br>        merged_api[&quot;components&quot;][&quot;schemas&quot;].update(api_spec.get(&quot;components&quot;, {}).get(&quot;schemas&quot;, {}))<br><br>    return merged_api</pre><h3>🔁 <strong>Smarter Initialization with Kubernetes</strong></h3><p>One of the coolest parts came later.</p><p>Since this aggregator was a microservice running in Kubernetes, I added a <strong>CronJob with an init container</strong> that retries fetching API specs until all APIs are live. This ensures we never end up with incomplete or incorrect documentation.</p><p>The service accepts all its config via <strong>environment variables</strong>, so we can point it to <strong>any number of APIs</strong> — making it flexible, portable, and incredibly easy to maintain. Let me share a Kubernetes job that can enhance the strength of this application.</p><pre>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: openapi-docs-generator<br>  namespace: documentation<br>spec:<br>  template:<br>    spec:<br>      initContainers:<br>      - name: wait-for-apis<br>        image: curlimages/curl:8.6.0<br>        command:<br>        - sh<br>        - -c<br>        - |<br>          endpoints=(<br>            &quot;https://api.example.com/app-a/openapi.json&quot;<br>            &quot;https://api.example.com/app-b/openapi.json&quot;<br>            &quot;https://api.example.com/app-c/openapi.json&quot;<br>          )<br><br>          max_retries=30<br>          delay=10<br><br>          for endpoint in &quot;${endpoints[@]}&quot;; do<br>            echo &quot;Waiting for $endpoint...&quot;<br>            retries=0<br>            until curl -sf &quot;$endpoint&quot;; do<br>              retries=$((retries + 1))<br>              if [ &quot;$retries&quot; -ge &quot;$max_retries&quot; ]; then<br>                echo &quot;Failed to reach $endpoint after $max_retries attempts.&quot;<br>                exit 1<br>              fi<br>              echo &quot;Retry $retries/$max_retries for $endpoint. Waiting $delay seconds...&quot;<br>              sleep &quot;$delay&quot;<br>            done<br>            echo &quot;$endpoint is available.&quot;<br>          done<br><br>          echo &quot;All API endpoints are reachable. Proceeding...&quot;<br>      containers:<br>      - name: openapi-aggregator<br>        image: ghcr.io/example/openapi-docs:latest<br>        env:<br>        - name: CONFIG_TITLE<br>          value: &quot;Unified API Reference&quot;<br>        - name: CONFIG_VERSION<br>          value: &quot;1.0.0&quot;<br>        - name: CONFIG_OPENAPI_VERSION<br>          value: &quot;3.1.0&quot;<br>        - name: CONFIG_DOCS_URL<br>          value: &quot;/docs&quot;<br>        - name: CONFIG_OPENAPI_URL<br>          value: &quot;/openapi.json&quot;<br>        - name: CONFIG_SOURCES<br>          value: |<br>            [<br>              {<br>                &quot;name&quot;: &quot;App A&quot;,<br>                &quot;prefix&quot;: &quot;/app-a&quot;,<br>                &quot;url&quot;: &quot;https://api.example.com/app-a/openapi.json&quot;<br>              },<br>              {<br>                &quot;name&quot;: &quot;App B&quot;,<br>                &quot;prefix&quot;: &quot;/app-b&quot;,<br>                &quot;url&quot;: &quot;https://api.example.com/app-b/openapi.json&quot;<br>              },<br>              {<br>                &quot;name&quot;: &quot;App C&quot;,<br>                &quot;prefix&quot;: &quot;/app-c&quot;,<br>                &quot;url&quot;: &quot;https://api.example.com/app-c/openapi.json&quot;<br>              }<br>            ]<br>        command: [&quot;python&quot;]<br>        args: [&quot;-m&quot;, &quot;hubapi.app&quot;]<br>      restartPolicy: OnFailure</pre><h3>Notes:</h3><ul><li>Replace the image with your actual container image.</li><li>The CONFIG_SOURCES value is a JSON array passed as a string, parsed by your application at runtime.</li><li>This assumes your app reads from environment variables or writes the config into a file (which it can do via initContainers too if needed).</li><li>If your app still expects a config.yaml, use a ConfigMap volume instead of environment variables.</li><li>The initContainer loops through the list of API endpoints.</li><li>It tries to reach each one using curl.</li><li>Retries each endpoint up to 30 times with 10 seconds between retries.</li><li>Only starts the main container once all endpoints are confirmed reachable.</li></ul><h3>🤔 <strong>Lessons from My Exploration</strong></h3><p>I was initially searching for a lot of third-party libraries online — and honestly, it wasted a lot of my time. I was also worried about:</p><ul><li>How would I upgrade the OpenAPI spec later?</li><li>What if I wanted to customize it?</li></ul><p>Using an external library would make those changes harder. But <strong>why add a dependency when FastAPI already gives you OpenAPI for free</strong>?</p><p>The OpenAPI structure is brilliantly organized — info, tags, paths, components, securitySchemes, etc.—and that makes it extremely flexible for combining specs and customizing how endpoints are grouped.</p><h3>🔐 Auth Support (Bonus)</h3><p>If any individual spec includes an Authorization security scheme, Swagger UI automatically shows the 🔐 <strong>Authorize</strong> button, making it easy for users to test authenticated endpoints in context.</p><h3>✅<strong> Final Thoughts</strong></h3><p>If you’re building a platform with multiple APIs, <strong>unifying documentation improves discoverability, developer onboarding, and overall usability</strong>. FastAPI made this much simpler than expected — and the result is a clean, centralized API explorer that anyone on the team can use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lz6jAqp1lFYsrI0sRP_55A.png" /><figcaption>Swagger UI Documentation</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63518e844986" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenTelemetry: Managing Logs in Modern Python Microservices]]></title>
            <link>https://medium.com/@sraza0098/opentelemetry-managing-logs-in-modern-python-microservices-e71cc5f5833f?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e71cc5f5833f</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 22:19:23 GMT</pubDate>
            <atom:updated>2025-06-26T22:19:23.670Z</atom:updated>
            <content:encoded><![CDATA[<p>Logging plays a critical role in any application. Without logs, engineers are essentially flying blind — unable to understand how the system behaves, how healthy it is, or how to debug issues efficiently.</p><p>As microservices architectures grow, so does the complexity of managing logs. Even with robust logging systems, it becomes challenging to trace and correlate events across distributed services. This is where <strong>OpenTelemetry</strong> shines.</p><p><strong>Why OpenTelemetry?</strong></p><p>I recently started using the OpenTelemetry Python SDK to improve logging and observability in a microservices-based system. OpenTelemetry helps by attaching unique identifiers to logs, making it easier to trace them across service boundaries. It also supports <strong>context propagation</strong>, allowing you to follow a request’s journey across different services.</p><p>To complement this, I used a package called <strong>opentelemetry-baggage</strong>, which carries context (like correlation IDs) between services. This is especially useful in microservices that communicate via messaging systems like Apache Pulsar.</p><p><strong>What is OpenTelemetry?</strong></p><blockquote><strong><em>OpenTelemetry</em></strong><em> is an open-source observability framework that helps generate, collect, and export telemetry data such as </em><strong><em>traces</em></strong><em>, </em><strong><em>metrics</em></strong><em>, and </em><strong><em>logs</em></strong><em>.</em></blockquote><p>It’s <strong>vendor-agnostic</strong> and works with popular tools like Jaeger, Prometheus, and Elastic. It’s supported across many programming languages — not just Python — making it ideal for polyglot environments.</p><p><strong>Installing OpenTelemetry in Python</strong></p><p>Here’s how to install the core packages:</p><pre>pip install opentelemetry-api<br>pip install opentelemetry-sdk</pre><p><strong>You can also install optional extensions:</strong></p><pre>pip install opentelemetry-exporter-{exporter}<br>pip install opentelemetry-instrumentation-{instrumentation}</pre><p><strong>And to use baggage and logging integration:</strong></p><pre>pip install opentelemetry-processor-baggage<br>pip install opentelemetry-instrumentation-logging</pre><p><strong>Initializing OpenTelemetry in Python</strong></p><p>The following setup initializes tracing and enables the baggage processor:</p><pre>from opentelemetry import trace<br>from opentelemetry.baggage import get_all<br>from opentelemetry.context import attach, detach<br>from opentelemetry.instrumentation.logging import LoggingInstrumentor<br>from opentelemetry.processor.baggage import ALLOW_ALL_BAGGAGE_KEYS, BaggageSpanProcessor<br>from opentelemetry.propagate import extract<br>from opentelemetry.sdk.trace import TracerProvider<br>from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor<br><br># --- Tracer Provider Setup ---<br>current_provider = trace.get_tracer_provider()<br>if not isinstance(current_provider, TracerProvider):<br>    provider = TracerProvider()<br>    provider.add_span_processor(BaggageSpanProcessor(ALLOW_ALL_BAGGAGE_KEYS))<br>    provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))<br>    trace.set_tracer_provider(provider)<br>else:<br>    provider = current_provider<br>    provider.add_span_processor(BaggageSpanProcessor(ALLOW_ALL_BAGGAGE_KEYS))<br><br>tracer = trace.get_tracer(__name__)</pre><p><strong>Structured Logging with Open Telemetry and Click</strong></p><p>Here’s how I integrate logging with click for CLI applications, enabling structured logs based on verbosity and environment:</p><pre>def setup_logging(verbosity=0, enable_otel_logging=None):<br>    enable_otel_logging = (<br>        enable_otel_logging<br>        or &quot;KUBERNETES_SERVICE_HOST&quot; in os.environ<br>        or &quot;OTEL_SERVICE_NAME&quot; in os.environ<br>    )<br><br>    if enable_otel_logging:<br>        LoggingInstrumentor().instrument(set_logging_format=False)<br>        handler = logging.StreamHandler()<br>        formatter = jsonlogger.JsonFormatter()<br>        handler.setFormatter(formatter)<br><br>        root_logger = logging.getLogger()<br>        root_logger.addHandler(handler)<br>        root_logger.addFilter(AddBaggageToLogFilter())<br>    else:<br>        logging.basicConfig(format=DEFAULT_LOG_FORMAT)<br><br>    # Set logging levels<br>    levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]<br>    level = levels[min(verbosity, len(levels)-1)]<br>    logging.getLogger().setLevel(level)</pre><p><strong>Context Propagation in Messaging (e.g., Pulsar)</strong></p><p>When using a message broker like <strong>Pulsar</strong>, OpenTelemetry can extract and restore trace context from message headers:</p><pre>incoming_properties = msg.properties()<br>propagated_ctx = extract(incoming_properties)<br>old_context = attach(propagated_ctx)</pre><p>You can then wrap your processing logic in a span:</p><pre>try:<br>    with tracer.start_as_current_span(self.subscription_name):<br>        logging.debug(f&quot;Processing msg with thread {threading.get_ident()=}&quot;)<br>        failures = messager.consume(msg)<br><br>        if failures.any_temporary():<br>            consumer.negative_acknowledge(msg)<br>        else:<br>            consumer.acknowledge(msg)<br>finally:<br>    detach(old_context)</pre><p><strong>Final Thoughts</strong></p><p>Using Open Telemetry has made a significant impact on how I manage logs across microservices. With tools like <strong>context propagation</strong>, <strong>baggage</strong>, and <strong>structured logging</strong>, it’s easier than ever to correlate events and debug issues in distributed systems.</p><p>If you’re dealing with a complex Python stack, especially with messaging systems like Pulsar, I highly recommend trying out Open Telemetry. It’s flexible, open source, and integrates well with modern observability tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e71cc5f5833f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JupyterHub with OIDC (Keycloak) and single-user images]]></title>
            <link>https://medium.com/@sraza0098/jupyterhub-with-oidc-keycloak-and-single-user-images-07a0f3a3fc0f?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/07a0f3a3fc0f</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[jupyter]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[data-scientist]]></category>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 12:23:18 GMT</pubDate>
            <atom:updated>2025-02-13T14:49:08.319Z</atom:updated>
            <content:encoded><![CDATA[<p>JupyterHub notebooks offer an excellent solution for data scientists and researchers to run their workflows and conduct project research. I’ve discovered a straightforward method to deploy JupyterHub on your Kubernetes cluster. Additionally, I’ve found an easy way to integrate OIDC-based authentication using Keycloak, a powerful open-source authentication provider. This setup ensures secure and efficient access to your JupyterHub environment, enhancing productivity and collaboration.</p><p>I’ve used Helm and Kustomize to deploy them in the cluster. These powerful tools make your deployment setup very developer-friendly and provide an easy way to deploy projects on the cluster. I have referred a really nice documentation which also helped my deployment even more simpler.<br><a href="https://z2jh.jupyter.org/en/stable/">Zero to JupyterHub with Kubernetes — Zero to JupyterHub with Kubernetes documentation</a></p><p>I have used the following structure to deploy the Jupyter Hub using Helm chart 4.1.0</p><p>You can also customize this application for multi-user support, including options for private user storage.</p><pre>Jupyter<br>  -base<br>    -kustomization.yaml<br>    -ingress.yaml<br>    -namespace.yaml<br>    -values.yaml<br>    -roles.yaml<br>    -secrets.yaml<br>  -envs<br>    -dev<br>      -kustomization.yaml</pre><p>Kustomization.yaml</p><pre>apiVersion: kustomize.config.k8s.io/v1beta1<br>kind: Kustomization<br><br>namespace: jupyter<br><br>resources:<br>  - ingress.yaml<br>  - namespace.yaml<br>  - roles.yaml<br>  - secrets.yaml<br><br>helmCharts:<br>  - name: jupyterhub<br>    repo: https://hub.jupyter.org/helm-chart/<br>    releaseName: jupyterhub<br>    namespace: jupyter<br>    version: 4.1.0      #use any latest version<br>    valuesFile: values.yaml</pre><p>namespace.yaml</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: jupyter</pre><pre>hub:<br>  baseUrl: /notebooks<br>  existingSecret: hub-secret-overrides<br>  config:<br>    JupyterHub:<br>      authenticator_class: generic-oauth<br>      hub_connect_url: http://hub.jupyter:8081<br>    Authenticator:<br>      auto_login: false<br>      enable_auth_state: true<br>      allow_all: true<br>    # GenericOAuthenticator params are injected by hub-secret-overrides, otherwise<br>    GenericOAuthenticator:<br>      authorize_url: yoururl<br>      token_url: yoururl<br>      oauth_callback_url: yoururl<br>      userdata_url: yoururl<br>      client_id: your-keycloak-client-id<br>      # client_secret: it will be added by my secret<br>      username_claim: preferred_username<br>      scope:<br>        - openid<br>    KubeSpawner:<br>      enable_user_namespaces: true<br>      user_namespace_template: {username}<br>  extraConfig:<br>    load_workspace.py: |<br>      print(&quot;loading workspace...&quot;)<br><br>  nodeSelector:<br>    role: general<br>singleuser:<br>  image:<br>    name: &quot;quay.io/jupyter/datascience-notebook&quot;<br>    tag: &quot;r-4.3.3&quot;<br>  serviceAccountName: default<br>  profileList:<br>    - display_name: &quot;Data Science (Python)&quot;<br>      description: &quot;Standard Python DS environment.&quot;<br>      default: true<br>    - display_name: &quot;Jupyter/Base-notebook&quot;<br>      description: &quot;Base Notebook environment.&quot;<br>      kubespawner_override:<br>        image: &quot;quay.io/jupyter/base-notebook:lab-4.3.5&quot;<br>    - display_name: &quot;Julia Environment&quot;<br>      description: &quot;Julia-based notebook environment.&quot;<br>      kubespawner_override:<br>        image: &quot;quay.io/jupyter/julia-notebook:lab-4.3.5&quot;<br>    - display_name: &quot;R Environment&quot;<br>      description: &quot;R-based notebook environment.&quot;<br>      kubespawner_override:<br>        image: &quot;quay.io/jupyter/r-notebook:r-4.4.2&quot;<br>    - display_name: &quot;Scipy Environment&quot;<br>      description: &quot;Scipy-based notebook environment.&quot;<br>      kubespawner_override:<br>        image: &quot;quay.io/jupyter/scipy-notebook:python-3.12&quot;<br>    - display_name: &quot;Tensorflow Environment&quot;<br>      description: &quot;Tensorflow-based notebook environment.&quot;<br>      kubespawner_override:<br>        image: &quot;quay.io/jupyter/tensorflow-notebook:ubuntu-24.04&quot;<br>    - display_name: &quot;PySpark Environment&quot;<br>      description: &quot;PySpark-based notebook environment.&quot;<br>      kubespawner_override:<br>        image: &quot;quay.io/jupyter/pyspark-notebook:hub-5.2.1&quot;<br>    - display_name: &quot;Pytorch Environment&quot;<br>      description: &quot;Pytorch-based notebook environment.&quot;<br>      kubespawner_override:<br>        image: &quot;quay.io/jupyter/pytorch-notebook:cuda11-ubuntu-24.04&quot;<br>  storage:<br>    type: static<br>    static:<br>      pvcName: pvc-{username}<br>    homeMountPath: /home/jovyan<br>  nodeSelector:<br>    role: processing<br>proxy:<br>  service:<br>    type: ClusterIP<br>  chp:<br>    nodeSelector:<br>      role: processing<br>scheduling:<br>  userScheduler:<br>    nodeSelector:<br>      role: general<br>prePuller:<br>  hook:<br>    nodeSelector:<br>      role: processing<br>debug:<br>  enabled: true</pre><p>roles.yaml</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: hub<br>rules:<br>  - apiGroups:<br>      - &quot;&quot;<br>    resources:<br>      - pods<br>      - namespaces<br>      - persistentvolumeclaims<br>      - secrets<br>      - services<br>    verbs:<br>      - get<br>      - watch<br>      - list<br>      - create<br>      - delete<br>  - apiGroups:<br>      - &quot;&quot;<br>    resources:<br>      - events<br>    verbs:<br>      - get<br>      - watch<br>      - list<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: hub<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: hub<br>subjects:<br>  - kind: ServiceAccount<br>    name: hub<br>    namespace: jupyter</pre><p>secrets.yaml</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: hub-secret-overrides<br>  annotations:<br>    argocd.argoproj.io/sync-options: ServerSideApply=true<br>data: {}<br>---<br>apiVersion: external-secrets.io/v1beta1<br>kind: ExternalSecret<br>metadata:<br>  name: hub-secret-overrides<br>spec:<br>  refreshInterval: 1m<br>  secretStoreRef:<br>    name: secret-store<br>    kind: ClusterSecretStore<br>  target:<br>    name: hub-secret-overrides<br>    creationPolicy: Merge<br>    template:<br>      data:<br>        values.yaml: |<br>          hub:<br>            config:<br>              GenericOAuthenticator:<br>                client_secret: {{.client_secret}}<br>  data:<br>    - secretKey: client_secret<br>      remoteRef:<br>        key: yourSecretKeyNameInAws<br>        property: anyPropertyKeyForYourSecret</pre><p>ingress.yaml</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: jupyter<br>  annotations:<br>    nginx.org/mergeable-ingress-type: minion<br>    nginx.org/websocket-services: proxy-public<br>    nginx.org/proxy-buffering: &quot;false&quot;<br>    nginx.org/location-snippets: |<br>      # include blocks/header_guards.conf;<br><br>      proxy_set_header Authorization $auth_header;<br><br>spec:<br>  ingressClassName: nginx<br>  rules:<br>    - host: anydomain.com<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: proxy-public<br>                port:<br>                  name: http</pre><p>envs/dev/kustomization.yaml</p><pre>apiVersion: kustomize.config.k8s.io/v1beta1<br>kind: Kustomization<br><br>resources:<br>  - ../../base</pre><p>I’ve provided multiple images for users to choose from, which you can either incorporate or discard as needed. JupyterHub also allows you to use custom images, offering additional flexibility.</p><p>I’ve stored the OIDC secret in AWS Secret Manager. To utilize this, I created an External Secret resource to fetch the secret and then a Secret resource to pass it to JupyterHub’s GenericOAuthenticator.</p><p>Additionally, I’ve set up an ingress and granted the necessary permissions to prevent blocking ingress requests. This setup is hosted on a public domain, provided you have a certificate from any certificate vendor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uPYs0ztLAvNvhk3xxIlpA.png" /><figcaption>Jupyter Hub Login without Keycloak</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsC119UehPiiM9EtUVpkTA.png" /><figcaption>Jupyter server options</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kvfNGTa-4IEYRM41i2GkQ.png" /><figcaption>Jupyter loading page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_5zJ5MKLJoA2Ia9YB5vTA.png" /><figcaption>Notebook loading page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5KxA4UffSCrSGaGHg4fJQ.png" /><figcaption>Notebook</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AUbEY0zMgxi_Vpsr6DHLw.png" /><figcaption>Notebook with cell</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07a0f3a3fc0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Log rotation in the ELK stack using ILM(Index Lifecycle) policy]]></title>
            <link>https://medium.com/@sraza0098/log-rotation-in-the-elk-stack-using-ilm-index-lifecycle-policy-0fcc011d0c2c?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fcc011d0c2c</guid>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 21:00:03 GMT</pubDate>
            <atom:updated>2025-01-15T21:00:03.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*g3nFp48w6PVbj-s_WWxlLw.png" /></figure><p>Running out of memory can be a major headache, often causing the Kibana UI to become inaccessible due to the ELK stack going down. Previously, I shared an article detailing the installation steps for the ELK stack using Helm and Kustomize (<a href="https://medium.com/@sraza0098/elk-stack-deployment-with-the-eck-operator-utilizing-both-kustomize-and-helm-fc5ed2dba8b7">https://medium.com/@sraza0098/elk-stack-deployment-with-the-eck-operator-utilizing-both-kustomize-and-helm-fc5ed2dba8b7</a>). Today, I’d like to show you how to prevent your ELK stack deployment from encountering this issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZ6ohuWW-YjeB910zhVhNw.png" /></figure><p>While addressing the ELK stack memory issue, I discovered that when using the Helm ECK operator, there’s no built-in policy for rolling out stored data. However, I found a workaround to resolve this issue and would like to share it with you all.</p><p>Before diving into the solution, I’d like to discuss the storage options.</p><h3>Block Storage</h3><ul><li><strong>Structure</strong>: Stores data in fixed-size blocks.</li><li><strong>Performance</strong>: High I/O performance.</li><li><strong>Use Cases</strong>: Ideal for databases and transactional systems.</li><li><strong>Examples</strong>: AWS EBS, Azure Disk.</li></ul><h3>File Storage</h3><ul><li><strong>Structure</strong>: Organizes data as files and folders.</li><li><strong>Performance</strong>: Suitable for shared access.</li><li><strong>Use Cases</strong>: Great for sharing data between containers.</li><li><strong>Examples</strong>: NTFS, EFS.</li></ul><p>I opted for file storage instead of block storage because Amazon EFS is expandable and can scale up or down based on requirements.</p><p>Based on my research, I found a couple of ways to solve this issue. The first is by using stack configuration policies, and the second is by utilizing the REST APIs provided by the ELK stack to create ILM policies and index templates</p><p>Stack configuration policy is a powerful tool provided by the ELK stack that allows you to create both ILM policies and indexes directly. However, this feature is labeled as an enterprise offering, requiring a paid subscription. Oh no, we’re stuck! What should we do now?</p><p>Here’s the trick: I decided to create a ConfigMap resource and mount it in a job that uses a curl image container. Using the Shell tool, we can execute curl commands to hit the REST APIs and create both the ILM policy and index template.</p><p>Let me share you the code and then I will explain you whats going on inside that.</p><p>configmap.yaml</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: ilm-and-index-template-config<br>  namespace: elk<br>data:<br>  ilm-policy.json: |<br>    {<br>        &quot;policy&quot;: {<br>            &quot;phases&quot;: {<br>                &quot;hot&quot;: {<br>                    &quot;actions&quot;: {<br>                        &quot;rollover&quot;: {<br>                            &quot;max_age&quot;: &quot;7d&quot;,<br>                            &quot;max_size&quot;:&quot;50gb&quot;,<br>                            &quot;max_docs&quot;: 10000000<br>                        },<br>                        &quot;set_priority&quot;: {<br>                            &quot;priority&quot;: 50<br>                        }<br>                    }<br>                },<br>                &quot;warm&quot;: {<br>                    &quot;actions&quot;: {<br>                        &quot;set_priority&quot;: {<br>                            &quot;priority&quot;: 25<br>                        }<br>                    }<br>                },<br>                &quot;cold&quot;: {<br>                    &quot;actions&quot;: {<br>                        &quot;set_priority&quot;: {<br>                            &quot;priority&quot;: 0<br>                        }<br>                    }<br>                },<br>                &quot;delete&quot;: {<br>                    &quot;min_age&quot;: &quot;7d&quot;,<br>                    &quot;actions&quot;: {<br>                        &quot;delete&quot;: {}<br>                    }<br>                }<br>            }<br>        }<br>    }<br>  index-template.json: |<br>    {<br>      &quot;index_patterns&quot;: [&quot;logs-*&quot;],<br>      &quot;data_stream&quot;: {},<br>      &quot;template&quot;: {<br>        &quot;settings&quot;: {<br>          &quot;number_of_shards&quot;: 1,<br>          &quot;number_of_replicas&quot;: 1,<br>          &quot;index.lifecycle.name&quot;: &quot;my-ilm-policy&quot;<br>        }<br>      }<br>    }</pre><p>ilm-job.yaml</p><pre>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: ilm-policy-job<br>spec:<br>  template:<br>    spec:<br>      containers:<br>        - name: apply-ilm-policy<br>          image: curlimages/curl:latest<br>          command: [&quot;/bin/sh&quot;, &quot;-c&quot;]<br>          args:<br>            - |<br>              # Apply ILM Policy<br>              echo &quot;Applying ILM Policy&quot;<br>              response=$(curl -kv -u elastic:${ELASTIC_PASSWORD} -X PUT &quot;https://elasticsearch-es-http:9200/_ilm/policy/my-ilm-policy&quot; -H &#39;Content-Type: application/json&#39; -d &quot;$(cat /etc/config/ilm-policy/ilm-policy.json)&quot;)<br>              echo &quot;ILM Policy Response: $response&quot;<br><br>              # Apply Index Template<br>              echo &quot;Applying Index Template&quot;<br>              response=$(curl -kv -u elastic:${ELASTIC_PASSWORD} -X PUT &quot;https://elasticsearch-es-http:9200/_index_template/my-index-template&quot; -H &#39;Content-Type: application/json&#39; -d &quot;$(cat /etc/config/index-template/index-template.json)&quot;)<br>              echo &quot;Index Template Response: $response&quot;<br>          env:<br>            - name: ELASTIC_PASSWORD<br>              valueFrom:<br>                secretKeyRef:<br>                  name: elasticsearch-es-elastic-user<br>                  key: elastic<br>          volumeMounts:<br>            - mountPath: /etc/config/ilm-policy<br>              name: ilm-policy-volume<br>            - mountPath: /etc/config/index-template<br>              name: index-template-volume<br>      volumes:<br>        - name: ilm-policy-volume<br>          configMap:<br>            name: ilm-and-index-template-config<br>            items:<br>              - key: ilm-policy.json<br>                path: ilm-policy.json<br>        - name: index-template-volume<br>          configMap:<br>            name: ilm-and-index-template-config<br>            items:<br>              - key: index-template.json<br>                path: index-template.json<br>      restartPolicy: Never<br>  backoffLimit: 4</pre><p>Let me explain what’s happening in the code above. A job is applied within your ELK stack namespace, running a container to execute a script. This script uses the CURL command to interact with the REST APIs provided by the ELK stack. I’ve added a ConfigMap resource to store both the ILM JSON and index template JSON, which are passed in the PUT request. Once these PUT requests are sent, the ELK stack will create both resources. These policies will manage your memory based on specific rules and actions. I highly recommend following this URL to learn more about the phases within the ELK stack.<br><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-index-lifecycle.html">Index lifecycle | Elasticsearch Guide [8.17] | Elastic</a></p><p>You can monitor the index template and ILM policy created by accessing the Kibana UI. Here are the steps to access them:</p><ol><li>Go to <strong>Stack Management</strong> in Kibana.</li><li>Click on <strong>Index Lifecycle Management</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQpX5eRUUuFu5X4vujzh9g.png" /><figcaption>ILM policy</figcaption></figure><p>You can also check the index template. The index template we create is linked to the ILM policy we established.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oites6ajZTZJxvkJdNUwQQ.png" /><figcaption>Index template</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fcc011d0c2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Prometheus to monitor metrics across microservices using both Kustomize and Helm]]></title>
            <link>https://medium.com/@sraza0098/deploying-prometheus-to-monitor-metrics-across-microservices-using-both-kustomize-and-helm-7f2eabb03378?source=rss-50b272340a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f2eabb03378</guid>
            <dc:creator><![CDATA[Shahid Raza]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 20:12:51 GMT</pubDate>
            <atom:updated>2025-01-15T20:12:51.978Z</atom:updated>
            <content:encoded><![CDATA[<p>Begin collecting your Kubernetes metrics with the powerful tool, Prometheus.</p><p>Prometheus is an open-source monitoring and alerting toolkit designed to collect and store metrics as time series data. It records real-time events, such as memory consumption, network utilization, and incoming requests, with timestamps. Prometheus uses a pull-based model to fetch data from endpoints, making it easy to integrate with various applications. <a href="https://www.howtogeek.com/devops/what-is-prometheus-and-why-is-it-so-popular/">It also supports powerful querying capabilities and alerting, helping teams monitor the health and performance of their systems effectively</a>.</p><p>I’d like to share a tutorial on deploying Prometheus declaratively using the powerful tool Helm. Additionally, I’ll demonstrate how to simplify this process further by incorporating Kustomize.</p><p>I have used the following structure to deploy the ELK stack using ECK operator.</p><pre>prometheus<br>  -base<br>    -kustomization.yaml<br>    -ingress.yaml<br>    -namespace.yaml<br>    -values.yaml<br>  -envs<br>    -dev<br>      -kustomization.yaml</pre><p>Kustomization.yaml</p><pre>apiVersion: kustomize.config.k8s.io/v1beta1<br>kind: Kustomization<br><br>namespace: monitoring<br><br>resources:<br>  - namespace.yaml<br>  - ingress.yaml<br><br>helmCharts:<br>  - name: prometheus<br>    repo: https://prometheus-community.github.io/helm-charts<br>    releaseName: prometheus<br>    namespace: monitoring<br>    version: 26.0.0   #use latest version<br>    valuesFile: values.yaml</pre><p>ingress.yaml</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: prometheus<br>  namespace: monitoring<br>  annotations:<br>    nginx.org/location-snippets: |<br>      auth_request off;<br>      include blocks/header_guards.conf;<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>    - host: &lt;&lt;REPLACE&gt;&gt;<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: prometheus-server<br>                port:<br>                  number: 9090<br>  tls:<br>    - hosts:<br>        - &lt;&lt;REPLACE&gt;&gt;<br>      secretName: prometheus-tls</pre><p>namespace.yaml</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: monitoring</pre><p>values.yaml</p><pre>server:<br>  service:<br>    servicePort: 9090<br>  persistentVolume:<br>    size: 10Gi</pre><p>Create a certificate for the Prometheus UI only if you plan to host it on a public domain. You can use cert-manager to issue this certificate. In my approach, I generated the certificate using cert-manager within the cluster, and the generated certificate was stored as a secret. You can see in my code that I use the prometheus-tls secret for ingress TLS.</p><p>If you don’t want to use ingress, you can remove that part of the code.</p><p>You can also set up a port forward to access the Prometheus UI. Use the following command:</p><pre>kubectl port-forward svc/prometheus-server 9090:9090</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXgo2_yTVUROaEpXav63Gw.png" /><figcaption>Prometheus UI</figcaption></figure><p>Prometheus scrapes data from Kubernetes applications using a pull-based model. Here’s how it works:</p><ol><li><strong>Service Discovery</strong>: Prometheus dynamically discovers the endpoints of your Kubernetes applications by querying the Kubernetes API. <a href="https://blog.sebastian-daschner.com/entries/prometheus-kubernetes-discovery">This ensures that Prometheus can automatically detect new pods and services as they are created or removed</a>.</li><li><strong>Scrape Configuration</strong>: You configure Prometheus with scrape jobs that specify which endpoints to scrape. <a href="https://devopscube.com/setup-prometheus-monitoring-on-kubernetes/">These configurations include details like the target endpoints, the metrics path (usually </a><a href="https://devopscube.com/setup-prometheus-monitoring-on-kubernetes/">/metrics), and the scrape interval</a>.</li><li><strong>Annotations</strong>: In Kubernetes, you can use annotations on your pods or services to indicate that they should be scraped by Prometheus. <a href="https://blog.sebastian-daschner.com/entries/prometheus-kubernetes-discovery">Common annotations include </a><a href="https://blog.sebastian-daschner.com/entries/prometheus-kubernetes-discovery">prometheus.io/scrape, </a><a href="https://blog.sebastian-daschner.com/entries/prometheus-kubernetes-discovery">prometheus.io/path, and </a><a href="https://blog.sebastian-daschner.com/entries/prometheus-kubernetes-discovery">prometheus.io/port</a></li><li><strong>Metrics Endpoints</strong>: The applications expose their metrics at specific HTTP endpoints. <a href="https://devopscube.com/setup-prometheus-monitoring-on-kubernetes/">Prometheus periodically sends HTTP requests to these endpoints to collect the metrics data</a>.</li><li><a href="https://devopscube.com/setup-prometheus-monitoring-on-kubernetes/"><strong>PromQL Queries</strong>: Once the data is collected, you can use Prometheus Query Language (PromQL) to query and analyze the metrics</a>.</li></ol><p>This setup allows Prometheus to efficiently monitor the health and performance of your Kubernetes applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f2eabb03378" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>