<?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 Amit Nath on Medium]]></title>
        <description><![CDATA[Stories by Amit Nath on Medium]]></description>
        <link>https://medium.com/@amitnath?source=rss-58c1ff4946a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EbFIQw3ziw67zT2IqcC8qg.jpeg</url>
            <title>Stories by Amit Nath on Medium</title>
            <link>https://medium.com/@amitnath?source=rss-58c1ff4946a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:47:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amitnath/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[How We Built a Multi-Region AWS Architecture for Global Data Compliance]]></title>
            <link>https://medium.com/@amitnath/how-we-built-a-multi-region-aws-architecture-for-global-data-compliance-4c2cf4c0a15b?source=rss-58c1ff4946a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c2cf4c0a15b</guid>
            <category><![CDATA[multi-region-architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[gdpr-compliance]]></category>
            <category><![CDATA[data-residency]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <dc:creator><![CDATA[Amit Nath]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 15:12:50 GMT</pubDate>
            <atom:updated>2026-04-10T15:12:50.247Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to keeping user data in-region with a single Next.js deployment</em></p><p>When we set out to build an image hosting platform, we knew data residency would be non-negotiable. Users in Europe expect their photos to stay in Europe. Users in Singapore shouldn’t have their data routed through Virginia. And as regulations like GDPR, India’s DPDP Act, and Australia’s Privacy Act continue to tighten, “we’ll deal with compliance later” is a liability, not a strategy.</p><p>This post breaks down the regional architecture we built on AWS — covering how we route requests to the right region, keep data physically separated, handle authentication across boundaries, and manage it all from a single codebase deployed once.</p><h3>The Problem: One App, Three Continents, Zero Data Leakage</h3><p>Our requirements were straightforward:</p><ol><li>Users in the EU should have their data stored exclusively in eu-west-1 (Ireland)</li><li>Users in the Americas should land in us-east-1 (N. Virginia)</li><li>Users in Asia-Pacific should land in ap-southeast-1 (Singapore)</li><li>No user data should cross regional boundaries — ever</li><li>A single domain should serve everyone — no region-specific subdomains</li></ol><p>The last point is key. We didn’t want the complexity of multi-domain deployments, regional CDN configurations, or geo-routed DNS. We wanted one app, one deployment, with per-request regional routing handled entirely in application logic.</p><h3>Architecture Overview</h3><p>Here’s the high-level picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dlX68i8EJQcYgtlrA6WTUA.png" /></figure><p>A single AWS Amplify app handles all traffic. On every request, the app resolves which region the user belongs to and routes all AWS SDK calls — DynamoDB, S3, Cognito — to that region’s resources. The only piece of shared state is a single global DynamoDB table that maps user emails to their assigned region.</p><h3>Per-Request Region Resolution</h3><p>The core of the system is a region resolver that runs on every server-side request. It follows a three-tier fallback:</p><h3>Tier 1: Saved User Region (Authenticated Requests)</h3><p>When a user is signed in, we extract their email from their JWT and look it up in the global user-regions table. This always returns the region they were assigned at signup — regardless of where they’re making the request from.</p><pre>User in Berlin signs up → assigned EU → data in eu-west-1<br>User travels to Tokyo  → still routes to eu-west-1</pre><p>This is critical for compliance. A German user on vacation in the US shouldn’t suddenly have their data created in us-east-1.</p><h3>Tier 2: Cloudflare Geo-Detection (New/Anonymous Users)</h3><p>For unauthenticated visitors, we read the CF-IPCountry header injected by Cloudflare. This ISO 3166-1 country code gets mapped to a region:</p><ul><li>US region: United States, Canada, Brazil, Mexico, and 50+ other countries in the Americas</li><li>EU region: Germany, France, UK, South Africa, Nigeria, UAE, and 80+ countries across Europe, Africa, and the Middle East</li><li>APAC region: Japan, Australia, India, Singapore, South Korea, and 40+ countries across Asia-Pacific</li></ul><h3>Tier 3: Default Fallback</h3><p>If geo-detection fails (missing header, unknown country code), we fall back to the REGION_DEFAULT environment variable — typically US.</p><h3>What Gets Resolved</h3><p>The resolver returns a complete RegionConfig object containing everything needed to interact with that region&#39;s AWS resources:</p><ul><li>AWS region identifier (us-east-1, eu-west-1, ap-southeast-1)</li><li>S3 bucket name</li><li>Seven DynamoDB table names (images, albums, shares, users, API keys, notifications, tags)</li><li>Cognito user pool ID, client ID, issuer URL, and domain</li></ul><p>No module-level singletons. No global state. Every request resolves its own config.</p><h3>Data Isolation by Design</h3><h4>Separate Everything Per Region</h4><p>Each region gets its own completely independent set of AWS resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPk5967Osk2yNapalQ1bWA.png" /></figure><p>There is no DynamoDB Global Tables replication. No S3 Cross-Region Replication. No Cognito user pool federation. Each region is a silo. A user’s images, metadata, albums, and authentication credentials all live exclusively in their assigned region.</p><h4>The One Exception: The Global Routing Table</h4><p>The only cross-region data is a single DynamoDB table in eu-west-1 that stores the mapping from email addresses to region labels. This table contains:</p><pre>{<br>  &quot;email&quot;: &quot;user@example.de&quot;,     // partition key<br>  &quot;regionLabel&quot;: &quot;EU&quot;,<br>  &quot;country&quot;: &quot;DE&quot;,<br>  &quot;createdAt&quot;: &quot;2025-01-15T...&quot;,<br>  &quot;updatedAt&quot;: &quot;2025-01-15T...&quot;<br>}</pre><p>This is metadata about <em>where</em> a user’s data lives — not the data itself. It’s the routing layer, not the storage layer. And it’s scoped to the minimum: email, region label, and country code.</p><h3>Authentication Across Regions</h3><p>Authentication is where multi-region architectures typically get messy. Here’s how we kept it clean.</p><h4>One Cognito Pool Per Region</h4><p>Each region has its own Cognito User Pool. When a user signs up:</p><ol><li>Their country is detected via CF-IPCountry</li><li>The country maps to a region (e.g., DE → EU)</li><li>The user is created in that region’s Cognito pool</li><li>The email → region mapping is written to the global table</li></ol><p>When a user signs in:</p><ol><li>Their email is looked up in the global table → returns region label</li><li>Authentication runs against that region’s Cognito pool</li><li>Tokens are set as httpOnly cookies</li></ol><h4>Cross-Region Token Verification</h4><p>JWTs issued by Cognito contain an iss (issuer) claim tied to the specific user pool. Our token verification logic:</p><ol><li>Decodes the JWT to extract the email</li><li>Looks up the expected region for that email</li><li>Verifies the JWT signature against that region’s JWKS endpoint</li><li>Fallback: If verification fails (e.g., stale region mapping), tries all other configured regions</li></ol><p>This fallback handles edge cases like users who existed before the global table was introduced — they might have tokens from any region. The system gracefully discovers the right one.</p><p>JWKS (JSON Web Key Sets) are cached per-issuer URL to avoid redundant network calls on every request.</p><h3>S3: Regional Buckets with No Public Access</h3><p>Each region has its own S3 bucket. Every bucket enforces:</p><ul><li>Server-side encryption (AES-256) on all objects</li><li>Public access fully blocked — no bucket policies allowing public reads</li><li>CORS configured only for the app’s domain</li></ul><p>Images are stored under a user-scoped prefix: users/{userId}/images/{imageId}.{ext}. Thumbnails go under users/{userId}/thumbnails/.</p><h4>No Direct S3 URLs</h4><p>We never expose S3 bucket URLs to clients. Instead, images are served through the app’s own /img/[...path] route, which:</p><ol><li>Resolves the requesting user’s region</li><li>Fetches the object from the correct regional S3 bucket</li><li>Streams it back with appropriate cache headers</li></ol><p>This means:</p><ul><li>Clients never learn the S3 bucket name or structure</li><li>Access control happens at the application layer</li><li>We can swap storage backends or add CDNs without changing URLs</li></ul><h4>Upload Flow</h4><p>Uploads use presigned PUT URLs — the server generates a time-limited URL pointing to the correct regional bucket, and the client uploads directly to S3. The server never handles the file bytes, but it controls <em>which bucket</em> the upload targets.</p><h3>Infrastructure as Code with Terraform</h3><p>The entire infrastructure is defined in Terraform with a modular structure:</p><pre>terraform/<br>├── main.tf              # Providers + module instantiation<br>├── global.tf            # Global user-regions table + cross-region IAM<br>├── route53.tf           # DNS + domain association<br>├── variables.tf         # Input configuration<br>├── modules/<br>│   ├── region/          # Instantiated 3x (US, EU, APAC)<br>│   │   ├── cognito.tf   # User pool + OAuth config<br>│   │   ├── dynamodb.tf  # All 7 tables with GSIs<br>│   │   ├── s3.tf        # Bucket + encryption + CORS<br>│   │   └── iam.tf       # SSR role permissions<br>│   └── amplify/         # Single app deployment</pre><h4>Adding a New Region</h4><p>Adding a fourth region (say, me-south-1 for Bahrain) requires:</p><ol><li>Add a new AWS provider in main.tf</li><li>Instantiate the region module with the new provider</li><li>Add environment variables (REGION_*_ME) to the Amplify config</li><li>Update the country-to-region mapping in application code</li></ol><p>No application architecture changes. No new deployments. The same app, the same codebase, just a new set of environment variables pointing to new resources.</p><h4>IAM: Least Privilege Across Regions</h4><p>Each region’s Amplify SSR execution role gets:</p><ul><li>Full access to its own region’s S3, DynamoDB, and Cognito resources</li><li>Limited access to the global user-regions table: only GetItem, PutItem, and UpdateItem — no Scan, no DeleteItem</li></ul><p>This ensures that even if one region’s execution environment is compromised, it cannot enumerate or delete global routing data.</p><h3>What This Architecture Gives You</h3><h4>GDPR Compliance</h4><p>European user data physically resides in eu-west-1 (Ireland). It never transits through US or APAC regions. The only cross-region data is the email-to-region mapping, which is minimal metadata — not personal content.</p><h4>Data Residency for APAC</h4><p>Users in India, Singapore, Australia, and Japan have their data in ap-southeast-1. As data localization requirements tighten across Asia-Pacific, this positions the platform ahead of regulatory changes.</p><h4>Operational Simplicity</h4><p>Despite spanning three continents, there is:</p><ul><li>One codebase — no region-specific forks</li><li>One deployment — Amplify in eu-west-1 serves everyone</li><li>One domain — no regional subdomains</li><li>One Terraform configuration — modular, repeatable, auditable</li></ul><h4>Performance Trade-offs</h4><p>We’re honest about the trade-off: since the app runs in eu-west-1, users in the US and APAC experience slightly higher latency for server-side rendering. However, the heavy operations — image uploads (direct to regional S3) and image serving (streamable) — go to the correct region. The SSR overhead is acceptable for a compliance-first architecture.</p><h3>Lessons Learned</h3><p>1. Resolve region per-request, not per-deployment. A single deployment that routes dynamically is far simpler to operate than three regional deployments with geo-routed DNS.</p><p>2. The global routing table is the linchpin. Keep it minimal (email → region), keep it fast (DynamoDB single-item reads), and keep it available (hosted in the same region as the app for lowest latency).</p><p>3. Cache AWS clients, not configs. Region configs should be resolved fresh per-request (a user’s region could theoretically change). But AWS SDK clients for a given region can be safely cached and reused.</p><p>4. Auth fallback across regions is essential. Users migrate, tokens persist, edge cases happen. A rigid “this token must be from this region’s Cognito” will break for real users. Graceful fallback across issuers saved us from support tickets.</p><p>5. Never expose bucket URLs. Routing images through your own endpoint gives you a compliance control point — you can log access, enforce authorization, and change backends without breaking URLs.</p><h3>Conclusion</h3><p>Building for data compliance doesn’t have to mean building three separate applications. With per-request region resolution, isolated AWS resources per region, and a minimal global routing table, you can serve a global user base from a single deployment while keeping every byte of user data exactly where it belongs.</p><p>The architecture is deliberately simple. No cross-region replication, no eventual consistency headaches, no multi-master conflicts. Each region is a clean silo. The global table is the only bridge, and it carries only routing metadata.</p><p>For teams evaluating multi-region architectures, the lesson is this: compliance is an architecture decision, not a checkbox. Build it into the data path from the start, and it becomes a feature of the system rather than a constraint bolted on later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c2cf4c0a15b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Agentic AI Risks Turning Brands Invisible]]></title>
            <link>https://medium.com/@amitnath/how-agentic-ai-risks-turning-brands-invisible-cbd5e2a4cfd0?source=rss-58c1ff4946a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbd5e2a4cfd0</guid>
            <dc:creator><![CDATA[Amit Nath]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 17:12:06 GMT</pubDate>
            <atom:updated>2026-02-03T17:12:06.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*to2x5mfqRm0Dr3dDBfpFFg.png" /></figure><p>A lot of brands learned an uncomfortable lesson after the COVID e-commerce spike — You can grow online sales and still <em>damage the business</em> — because the offline shelf isn’t just a channel. It’s <strong>brand presence</strong>, <strong>habit</strong>, and <strong>defensive territory</strong>.</p><p>When brands pushed too hard into DTC (pricing sharper, promos louder, assortment “better online”), retailers noticed. The quiet consequence wasn’t a nasty email. It was <strong>less love in-store</strong>: fewer facings, weaker endcaps, slower replenishment priority — because shelf space is finite and fiercely competed. Academic and retail literature has long treated shelf space as a scarce asset that affects what customers notice and buy.</p><p>Then the post-COVID rebalancing made the trade-off obvious. In Great Britain, online share hit a record high of <strong>37% in February 2021</strong> and then generally fell back below pre-pandemic levels later on. Many brands stopped chasing “maximum online share” and started protecting distribution again. In public terms, you saw it in moves like Nike emphasizing a rebuild of wholesale relationships after a DTC-heavy period.</p><p>Now agentic commerce potentially can push this balance further towards offline.</p><h3>Agentic Commerce: When Agents Become the Storefront</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SbuUGyHM-I0eynoo.png" /></figure><p>Agentic commerce protocols are building a standardised way for AI agents to discover products, compare options, and complete checkout across merchants.</p><ul><li><strong>UCP</strong> (Universal Commerce Protocol) was announced in January 2026 by Google with partners including Shopify, positioned as an open standard for agentic shopping across surfaces like Search and Gemini. (<a href="https://blog.google/products/ads-commerce/agentic-commerce-ai-tools-protocol-retailers-platforms/?utm_source=chatgpt.com">blog.google</a>)</li><li><strong>ACP</strong> (Agentic Commerce Protocol) is an open standard maintained by OpenAI and Stripe, currently described as beta, and used to power “Instant Checkout” in ChatGPT. (<a href="https://github.com/agentic-commerce-protocol/agentic-commerce-protocol?utm_source=chatgpt.com">GitHub</a>)</li></ul><p>In plain language: the “digital aisle” shifts from <strong>your website/app</strong> to <strong>the agent’s recommendation space</strong>.</p><p>And that’s where the online brand identity starts getting compressed.</p><h3>The “brandless checkout” effect</h3><p>In an agent-led flow, the customer journey becomes:</p><blockquote><strong><em>Intent → shortlist → decision → buy (inside the agent)</em></strong></blockquote><p>Instead of:</p><blockquote><strong><em>Brand world → merchandising → discovery → cross-sell → checkout (on your site)</em></strong></blockquote><p>Even if your brand is named, your <em>presence</em> is reduced to a few bullets:</p><ul><li>Price</li><li>Delivery promise</li><li>Return policy</li><li>Rating</li></ul><p>The agent is now front-of-house.<br> Your brand is relegated to back-end logic.</p><p>This is the <strong>brand identity risk</strong>: the shopper no longer spends time inside your world. They don’t see your storytelling, your UI, your reasons to buy. They see a system output.</p><p>The agent’s job is to optimize. Not to inspire.</p><p>And the protocols — ACP and UCP — are designed to make that frictionless.</p><h3>The hidden problem: profit doesn’t come from the hero SKU</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*AzLCuBWwKpg1V2JssSZH5w.png" /></figure><p>Retail margins rarely come from the main product. They come from:</p><ul><li><strong>Accessories</strong></li><li><strong>Spares and consumables</strong></li><li><strong>Bundles/kits</strong></li><li><strong>Installation and services</strong></li><li><strong>Protection plans and memberships</strong></li></ul><p>Protection plans, for example, consistently deliver <strong>4–5% attach rate</strong> in e-commerce — and are often highly profitable. Best Buy has publicly tied gross margin improvements to growth in <strong>paid memberships</strong>, warranties, and value-added services.</p><p>But agentic commerce threatens this margin mix.</p><p>When agents optimize for “best match” and fast checkout, they often:</p><ul><li>Default to single-item purchases</li><li>Skip attach flows</li><li>Omit accessories unless prompted</li><li>Avoid recommending service plans unless fully encoded</li></ul><p>Even if conversion rates rise, <strong>contribution margin can shrink</strong> if your high-value attachments aren’t included.</p><p>That’s the profit trap.</p><h3>Why agentic commerce threatens this margin mix</h3><p>When the agent optimizes for “best match” and completes purchase quickly, it can unintentionally:</p><ul><li>reduce attach opportunities (fewer “moments” to pitch add-ons)</li><li>default to single-item purchases</li><li>treat accessories/spares as “optional” unless explicitly prompted</li><li>route service plans away from brands unless the offer is machine-legible and easy to add</li></ul><p>So even if agentic commerce <strong>increases conversion</strong>, it can <strong>decrease contribution margin</strong> if attachments collapse.</p><p>That’s the profit trap.</p><h3>What breaks first when the agent is the storefront</h3><h4>1) Cross-sell becomes a logic problem, not a design problem</h4><p>On your site, you can guide: “People also buy…”, bundles, comparison tables, curated kits.</p><p>In agentic flows, you must encode:</p><ul><li>compatibility rules</li><li>“must-have” accessories vs “nice-to-have”</li><li>bundle economics (why a kit is better value)</li><li>service plan relevance triggers (high-risk items, heavy users, families, etc.)</li></ul><p>If the agent can’t <em>prove</em> compatibility or value, it won’t recommend confidently.</p><h4>2) Brand differentiation gets flattened into comparable attributes</h4><p>Agents excel at comparing structured facts (price, availability, delivery, returns). They struggle with intangible brand magic unless you translate it into proof.</p><h4>3) Your retail shelf advantage can disappear digitally</h4><p>You might have amazing in-store presence — yet the agent doesn’t “see” it unless store inventory, pickup windows, in-store returns, or service coverage are exposed as structured signals the agent can use.</p><h3>The bottom line</h3><p>“Protecting shelves” was an omnichannel survival strategy: keep physical presence, defend identity, avoid being replaced.</p><p>Agentic commerce creates a new shelf — <strong>the agent’s shortlist</strong> — where branding is thinner, decisions are faster, and profit drivers like accessories and service plans can get squeezed unless you redesign for them.</p><p>The winners won’t be the brands that scream louder.</p><p>They’ll be the ones who:</p><ul><li>Are easiest for agents to understand</li><li>Are safest for agents to recommend</li><li>Can preserve margin through encoded attachments</li><li>Do it without triggering offline retail backlash</li></ul><h3>Final thought</h3><p>You protected your shelf.</p><p>Now you need to <strong>rebuild your presence inside the agent</strong> — not just to win the conversion, but to keep the margin and preserve the brand.</p><p>Because in this new era, the screen is gone.</p><p>The agent is the store.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbd5e2a4cfd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Sling Context-Aware Configurations with AEM]]></title>
            <link>https://medium.com/@amitnath/leveraging-sling-context-aware-configurations-with-aem-de0b160c1675?source=rss-58c1ff4946a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/de0b160c1675</guid>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[sling]]></category>
            <category><![CDATA[context-aware]]></category>
            <category><![CDATA[multisite]]></category>
            <dc:creator><![CDATA[Amit Nath]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 11:35:40 GMT</pubDate>
            <atom:updated>2024-10-21T11:35:40.942Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Adobe Experience Manager (AEM) is a powerful content management system that allows organizations to deliver personalized digital experiences across multiple channels. One of the key features that enable this flexibility is the use of Sling Context-Aware Configurations (CAConfigs). By leveraging CAConfigs, developers can create components and services that adapt their behavior based on the content hierarchy, making applications more modular, maintainable, and scalable.</p><p>In this blog post, we’ll explore what Sling Context-Aware Configurations are, why they are important in AEM development, and how you can implement them to enhance your AEM projects.</p><h3>Understanding Sling Context-Aware Configurations</h3><h3>What Are Context-Aware Configurations?</h3><p>Sling Context-Aware Configurations provide a way to define and access configurations that are specific to a certain context within the content hierarchy. Instead of using global configurations or hardcoded values, CAConfigs allow for configurations to be resolved dynamically based on the resource’s location in the repository.</p><p>This means that different parts of your content tree can have different configurations, and components or services can automatically pick up the appropriate configuration based on where they are being used.</p><h3>Benefits of Using CAConfigs</h3><ul><li><strong>Flexibility</strong>: Configure components differently in various parts of the site without code changes.</li><li><strong>Maintainability</strong>: Centralize configuration management, reducing duplication and errors.</li><li><strong>Reusability</strong>: Develop generic components that adapt to different contexts, promoting code reuse.</li><li><strong>Scalability</strong>: Easily manage configurations as your content grows and changes over time.</li></ul><h3>How Context-Aware Configurations Work in AEM</h3><p>AEM leverages the Apache Sling framework, which uses a resource-based approach for content management. CAConfigs are built on top of Sling’s resource resolution capabilities.</p><h3>Key Concepts</h3><ul><li><strong>Configuration Resource</strong>: A node in the repository that contains configuration properties.</li><li><strong>Context Path</strong>: The content path relative to which the configuration is resolved.</li><li><strong>Configuration Buckets</strong>: Special nodes (e.g., sling:configs) where configurations are stored.</li></ul><h3>Configuration Resolution Process</h3><p>When a component or service requests a configuration, Sling searches for the nearest configuration resource in the content hierarchy. The search starts from the current resource and moves up the tree until it finds a configuration that matches the requested name.</p><h3>Implementing CAConfigs in AEM</h3><h3>Step 1: Define a Configuration Interface</h3><p>First, you need to define a Java interface that represents your configuration. This interface uses annotations to describe the configuration properties.</p><pre>package com.example.core.config;<br><br>import org.apache.sling.caconfig.annotation.Configuration;<br>import org.apache.sling.caconfig.annotation.Property;<br><br>@Configuration(label = &quot;Site Configuration&quot;, description = &quot;Site-specific configurations.&quot;)<br>public @interface SiteConfig {<br><br>    @Property(label = &quot;Site Name&quot;, description = &quot;The name of the site.&quot;)<br>    String siteName() default &quot;Default Site&quot;;<br><br>    @Property(label = &quot;Enable Feature X&quot;, description = &quot;Flag to enable or disable Feature X.&quot;)<br>    boolean enableFeatureX() default false;<br>}</pre><h3>Step 2: Create Configuration Resources</h3><p>Next, create configuration nodes in the repository under the /conf folder. These nodes store the actual configuration values.</p><ul><li><strong>Configuration Path Structure</strong>:</li></ul><pre>/conf<br>  /&lt;site-name&gt;<br>    /settings<br>      /wcm<br>        /sling:configs<br>          /com.example.core.config.SiteConfig<br>            - siteName = &quot;My Site&quot;<br>            - enableFeatureX = true</pre><p>For example, to configure “Site A”, you would create:</p><pre>/conf/siteA/settings/wcm/sling:configs/com.example.core.config.SiteConfig</pre><h3>Step 3: Accessing Configurations in Components</h3><p>In your Sling Models or services, you can access the configurations using the ConfigurationBuilder.</p><p><strong>Example Sling Model</strong>:</p><pre>package com.example.core.models;<br><br>import javax.annotation.PostConstruct;<br><br>import org.apache.sling.api.SlingHttpServletRequest;<br>import org.apache.sling.caconfig.ConfigurationBuilder;<br>import org.apache.sling.models.annotations.Model;<br>import org.apache.sling.models.annotations.injectorspecific.Self;<br><br>import com.example.core.config.SiteConfig;<br><br>@Model(adaptables = SlingHttpServletRequest.class)<br>public class SiteInfoModel {<br><br>    @Self<br>    private SlingHttpServletRequest request;<br><br>    private String siteName;<br>    private boolean featureXEnabled;<br><br>    @PostConstruct<br>    protected void init() {<br>        ConfigurationBuilder configBuilder = request.adaptTo(ConfigurationBuilder.class);<br>        if (configBuilder != null) {<br>            SiteConfig siteConfig = configBuilder.as(SiteConfig.class);<br>            if (siteConfig != null) {<br>                siteName = siteConfig.siteName();<br>                featureXEnabled = siteConfig.enableFeatureX();<br>            }<br>        }<br>    }<br><br>    public String getSiteName() {<br>        return siteName;<br>    }<br><br>    public boolean isFeatureXEnabled() {<br>        return featureXEnabled;<br>    }<br>}</pre><h3>Step 4: Using Configurations in HTL Scripts</h3><p>In your HTL scripts, you can use the Sling Model to display configuration values or conditionally render content.</p><p><strong>Example HTL Script</strong>:</p><pre>&lt;sly data-sly-use.siteInfo=&quot;com.example.core.models.SiteInfoModel&quot;&gt;<br>    &lt;h1&gt;Welcome to ${siteInfo.siteName}&lt;/h1&gt;<br><br>    &lt;sly data-sly-test=&quot;${siteInfo.featureXEnabled}&quot;&gt;<br>        &lt;!-- Render Feature X components --&gt;<br>        &lt;div&gt;Feature X is enabled!&lt;/div&gt;<br>    &lt;/sly&gt;<br>&lt;/sly&gt;</pre><h3>Step 5: Testing Configuration Resolution</h3><p>Ensure that your configurations are resolving correctly by:</p><ul><li>Placing components under different content paths and verifying they pick up the correct configurations.</li><li>Using the Context-Aware Configuration Debugger available at /system/console/caconfig to troubleshoot.</li></ul><h3>Best Practices</h3><ul><li><strong>Organize Configurations Logically</strong>: Structure your configurations under /conf in a way that mirrors your content hierarchy.</li><li><strong>Use Meaningful Names</strong>: Use fully qualified class names for configuration names to avoid conflicts.</li><li><strong>Handle Null Values</strong>: Always check for null when accessing configurations to prevent NullPointerExceptions.</li><li><strong>Leverage Default Values</strong>: Define default values in your configuration interfaces to ensure components have fallback values.</li><li><strong>Secure Configuration Access</strong>: Ensure that proper permissions are set so that only authorized users can modify configurations.</li></ul><h3>Advanced Usage</h3><h3>Inheriting Configurations</h3><p>CAConfigs support inheritance, allowing configurations to be defined at higher levels in the content tree and overridden in lower levels.</p><h3>Dynamic Configurations</h3><p>You can also programmatically access configurations using the ConfigurationResourceResolver or inject configurations directly into Sling Models using @Source annotations.</p><p><strong>Example Using </strong><strong>@Source</strong>:</p><pre>@Model(adaptables = SlingHttpServletRequest.class)<br>public class SiteInfoModel {<br><br>    @Self<br>    private SlingHttpServletRequest request;<br><br>    @Inject<br>    @Source(&quot;caconfig&quot;)<br>    private SiteConfig siteConfig;<br><br>    // Use siteConfig directly<br>}</pre><h3>Conclusion</h3><p>Leveraging Sling Context-Aware Configurations in AEM allows developers to create flexible and scalable applications. By defining configurations that adapt based on the content hierarchy, you can build components and services that are truly context-aware.</p><p>Implementing CAConfigs enhances maintainability, promotes code reuse, and improves the overall architecture of your AEM projects. Whether you’re developing for multi-site setups, handling localization, or managing feature toggles, CAConfigs provide a robust solution for managing configurations in a dynamic and efficient way.</p><h3>Additional Resources</h3><ul><li><a href="https://experienceleague.adobe.com/docs/experience-manager-cloud-service/content/implementing/developing/full-stack/configuration/caconfig.html">Adobe Experience Manager Documentation</a></li><li><a href="https://sling.apache.org/documentation/bundles/context-aware-configuration/context-aware-configuration.html">Apache Sling Context-Aware Configuration</a></li><li>Using Context-Aware Configurations in AEM</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de0b160c1675" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Site Factory Configurations in AEM with OSGi]]></title>
            <link>https://medium.com/@amitnath/multi-site-factory-configurations-in-aem-with-osgi-3dce1a424d44?source=rss-58c1ff4946a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dce1a424d44</guid>
            <category><![CDATA[adobe-experience-manager]]></category>
            <category><![CDATA[osgi]]></category>
            <category><![CDATA[aem]]></category>
            <dc:creator><![CDATA[Amit Nath]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 23:51:22 GMT</pubDate>
            <atom:updated>2024-09-02T23:51:22.291Z</atom:updated>
            <content:encoded><![CDATA[<p>In Adobe Experience Manager (AEM), managing configurations for multiple sites or tenants can become complex, especially when each site requires different settings. This complexity can be efficiently handled using OSGi factory configurations. This blog will guide you through the process of implementing site-specific configurations using a single OSGi configuration file (cfg.json), making your AEM application scalable and maintainable.</p><h3>Understanding OSGi Factory Configurations</h3><p>OSGi (Open Service Gateway Initiative) is a framework that allows developers to modularize their applications. In AEM, OSGi is used extensively to manage configurations and services.</p><p>A factory configuration in OSGi allows multiple instances of a service to be configured and managed separately. Each instance of the service can have its own configuration, making it ideal for scenarios where different sites or tenants need distinct settings.</p><h3>Why Use Factory Configurations?</h3><p>In a multi-site AEM setup, different sites may need different configurations for services such as third-party integrations, content indexing, or API connections. Using a single OSGi configuration file (cfg.json) for all these sites could lead to a bloated and hard-to-manage configuration. Factory configurations allow you to:</p><ul><li><strong>Centralize Configuration Management</strong>: Manage all site-specific configurations in a single file.</li><li><strong>Reduce Complexity</strong>: Keep your configurations organized and reduce the risk of errors.</li><li><strong>Improve Scalability</strong>: Easily add or remove configurations as the number of sites grows.</li></ul><h3>Step-by-Step Implementation</h3><p>Let’s walk through the process of implementing site-specific configurations using OSGi factory configurations.</p><h4>1. Define the Factory Configuration Interface</h4><p>First, define an OSGi configuration interface that will hold the site-specific settings. This interface will be used to generate multiple instances of the configuration.</p><pre>import org.osgi.service.metatype.annotations.AttributeDefinition;<br>import org.osgi.service.metatype.annotations.ObjectClassDefinition;<br><br>@ObjectClassDefinition(name = &quot;Search Engine Configurations&quot;)<br>public @interface SearchEngineConfig {<br><br>    @AttributeDefinition(name = &quot;Site Identifier&quot;)<br>    String siteId() default &quot;&quot;;<br><br>    @AttributeDefinition(name = &quot;API ID&quot;)<br>    String apiId() default &quot;&quot;;<br><br>    @AttributeDefinition(name = &quot;API Key&quot;)<br>    String apiKey() default &quot;&quot;;<br><br>    @AttributeDefinition(name = &quot;Search Index&quot;)<br>    String searchIndex() default &quot;&quot;;<br><br>    @AttributeDefinition(name = &quot;Best Seller Index&quot;)<br>    String bestSellerIndex() default &quot;&quot;;<br>}</pre><p>In this example, the SearchEngineConfig interface defines various settings related to a search engine integration, with each setting prefixed by the site ID to distinguish configurations for different sites.</p><h4>2. Register the Service as a Factory Component</h4><p>Next, implement the service that will use these configurations. This service needs to be registered as a factory component by specifying the configurationPid in the @Component annotation.</p><pre>import org.osgi.service.component.annotations.Component;<br>import org.osgi.service.component.annotations.Activate;<br>import org.osgi.service.component.annotations.Modified;<br>import org.osgi.service.metatype.annotations.Designate;</pre><pre><a href="http://twitter.com/Component">@Component</a>(service = SearchService.class, configurationPid = &quot;com.example.SearchEngineConfig&quot;)<br><a href="http://twitter.com/Designate">@Designate</a>(ocd = SearchEngineConfig.class, factory = true)<br>public class SearchServiceImpl implements SearchService {</pre><pre>private SearchEngineConfig searchEngineConfig;</pre><pre><a href="http://twitter.com/Activate">@Activate</a><br>    <a href="http://twitter.com/Modified">@Modified</a><br>    protected void activate(SearchEngineConfig config) {<br>        this.searchEngineConfig = config;<br>    }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void performSearch() {<br>        String siteId = searchEngineConfig.siteId();<br>        String apiId = searchEngineConfig.apiId();<br>        // Use the site-specific configuration as needed<br>    }<br>}</pre><p>Here, the SearchServiceImpl service is designed to work with site-specific configurations. The @Designate annotation indicates that this service can have multiple instances, each configured using the SearchEngineConfig interface.</p><h4>3. Creating and Managing Site-Specific Configurations</h4><p>Each site will have its own configuration file, and these files will be managed centrally. These files are stored in the OSGI-INF directory of your project.</p><p>For example:</p><ul><li>OSGI-INF/config/com.example.SearchEngineConfig-siteA.cfg.json:</li></ul><pre>{<br>  &quot;siteId&quot;: &quot;siteA&quot;,<br>  &quot;apiId&quot;: &quot;siteAApiId&quot;,<br>  &quot;apiKey&quot;: &quot;siteAApiKey&quot;,<br>  &quot;searchIndex&quot;: &quot;siteASearchIndex&quot;,<br>  &quot;bestSellerIndex&quot;: &quot;siteABestSellerIndex&quot;<br>}</pre><ul><li>OSGI-INF/config/com.example.SearchEngineConfig-siteB.cfg.json:</li></ul><pre>{<br>  &quot;siteId&quot;: &quot;siteB&quot;,<br>  &quot;apiId&quot;: &quot;siteBApiId&quot;,<br>  &quot;apiKey&quot;: &quot;siteBApiKey&quot;,<br>  &quot;searchIndex&quot;: &quot;siteBSearchIndex&quot;,<br>  &quot;bestSellerIndex&quot;: &quot;siteBBestSellerIndex&quot;<br>}</pre><p>These configuration files will create separate instances of SearchServiceImpl for each site, each with its own settings.</p><h4>4. Accessing the Configuration Based on Site</h4><p>In your service implementation, you can now access the correct configuration instance based on the current site context. There are a couple of ways to do this:</p><p>Option 1: Inject Multiple Configurations</p><p>If you have a small number of sites, you can inject multiple configurations and select the appropriate one at runtime.</p><pre>import org.osgi.service.component.annotations.Component;<br>import org.osgi.service.component.annotations.Reference;<br>@Component(service = SearchService.class, configurationPid = &quot;com.example.SearchEngineConfig&quot;)<br>@Designate(ocd = SearchEngineConfig.class, factory = true)<br>public class SearchServiceImpl implements SearchService {<br>private Map&lt;String, SearchEngineConfig&gt; configMap = new HashMap&lt;&gt;();<br>    @Activate<br>    @Modified<br>    protected void activate(Map&lt;String, SearchEngineConfig&gt; configs) {<br>        for (SearchEngineConfig config : configs.values()) {<br>            configMap.put(config.siteId(), config);<br>        }<br>    }<br>    public SearchEngineConfig getConfigForSite(String siteId) {<br>        return configMap.get(siteId);<br>    }<br>    @Override<br>    public void performSearch() {<br>        String currentSiteId = determineCurrentSiteId(); // Logic to determine the current site<br>        SearchEngineConfig config = getConfigForSite(currentSiteId);<br>        if (config != null) {<br>            // Use the site-specific configuration<br>        }<br>    }<br>}</pre><p>Option 2: Dynamically Inject Based on Site ID</p><p>You can dynamically retrieve the configuration based on the site identifier by registering the configurations with specific service properties and using an OSGi filter to select the correct one.</p><h3>Conclusion</h3><p>Managing configurations in a multi-site AEM setup can be complex, but OSGi factory configurations provide a powerful and flexible solution. By using factory configurations, you can maintain all site-specific settings in a single file, keep your configurations organized, and ensure your AEM application scales smoothly as the number of sites increases.</p><p>This approach not only simplifies configuration management but also enhances the maintainability and scalability of your AEM application. As your project grows, you can easily extend this pattern to manage other site-specific settings, ensuring that each site operates with the appropriate configuration.</p><p>By following this guide, you can implement a robust and scalable configuration strategy that meets the demands of a multi-site AEM environment, enabling your teams to manage and maintain site-specific configurations with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dce1a424d44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ecommerce SEO Optimization: Striking a Balance between CSR and SSR]]></title>
            <link>https://medium.com/@amitnath/ecommerce-seo-optimization-striking-a-balance-between-csr-and-ssr-add7dbbc18ac?source=rss-58c1ff4946a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/add7dbbc18ac</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[client-side-rendering]]></category>
            <category><![CDATA[ecommerce-web-development]]></category>
            <dc:creator><![CDATA[Amit Nath]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 00:42:30 GMT</pubDate>
            <atom:updated>2023-07-03T17:08:18.776Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Search Engine Optimization or SEO is the process of optimizing an website so that it can rank higher in search engines. This can be done by optimizing the website’s content, structure, and code for relevant keywords.</p><p>In today’s digital era, having a strong online presence is crucial for the success of any e-commerce business. With the increasing competition in the online marketplace, it is essential to implement effective strategies to drive traffic and improve visibility for your online store. One of the most powerful techniques you can utilize is SEO. By implementing effective SEO techniques in e-commerce website, you can attract more organic traffic to your store, which can lead to increased sales and revenue.</p><p>In this blog post, we will discuss the importance of SEO for e-commerce business and how to implement it on your website. We will also cover the different approaches to rendering web pages, CSR and SSR, and how they impact SEO.</p><p>By the end of this blog post, you will have a better understanding of e-commerce SEO and how to implement it on your website. You will also be able to decide which approach to rendering web pages is best for your SEO needs.</p><h4>Here are some of the benefits of SEO in e-commerce:</h4><ul><li>Increased organic traffic to your store</li><li>Increased sales and revenue</li><li>Improved brand visibility</li><li>Enhanced user experience</li><li>Improved search engine rankings</li></ul><p>If you are looking to improve your e-commerce SEO, then you should follow these tips:</p><ul><li>Do keyword research</li><li>Optimize your Product Detail Page (PDP) and Product Listing Page (PLP) pages.</li><li>Create high-quality content</li><li>Build backlinks</li><li>Use social media</li><li>Make your website mobile-friendly</li><li>Keep your website up-to-date</li></ul><p>By following these tips, you can improve your e-commerce SEO and attract more organic traffic to your store.</p><h3>Keyword Research</h3><p>Keywords play a vital role in SEO, and conducting thorough keyword research is the first step towards optimizing your e-commerce website. Start by identifying relevant keywords and phrases that align with your products or services. Use keyword research tools to identify high-volume and low-competition keywords that can help you rank higher in search engine results pages (SERPs).</p><p>It is crucial to consider long-tail keywords that are specific to your products or services. For example, instead of targeting a broad keyword like “shoes,” focus on more specific terms like “women’s running shoes” or “affordable leather boots.” Long-tail keywords tend to have lower competition and higher conversion rates.</p><p>Link: <a href="https://backlinko.com/keyword-research-tools">Keyword Research Tools</a></p><h3>On-Page Optimization</h3><p>On-page optimization involves optimizing various elements on your website to make it search engine-friendly. Here are some essential on-page optimization techniques for your e-commerce store:</p><h4>Title Tags and Meta Descriptions</h4><p>Ensure that each product page has a unique and descriptive title tag and meta description. Include relevant keywords naturally and make sure they accurately represent the content of the page.</p><h4>URL Structure</h4><p>Optimize your URLs to be concise, descriptive, and include relevant keywords. Avoid using long strings of numbers or irrelevant characters in your URLs.</p><h4>Product Descriptions</h4><p>Craft unique, engaging, and keyword-rich product descriptions. Avoid duplicating content from manufacturers or other websites, as it can harm your search rankings. Include relevant information, benefits, and usage instructions to help potential customers make informed decisions.</p><h4>Image Optimization</h4><p>Optimize your product images by using descriptive file names and alt tags. This helps search engines understand what the image represents and improves the chances of appearing in image search results.</p><h3>Site Architecture and Navigation</h3><p>A well-structured and user-friendly site architecture is essential for both search engines and visitors. Here are a few tips to improve your e-commerce site’s architecture:</p><h4>Clear Category Hierarchy</h4><p>Organize your products into logical categories and subcategories. This helps users navigate through your site easily and allows search engines to understand the structure of your website.</p><h4>Internal Linking</h4><p>Implement internal links between related products, categories, and content pages. Internal linking helps search engines discover and index your pages more efficiently, improves user experience, and encourages visitors to explore more of your website.</p><h4>Mobile-Friendly Design</h4><p>With the increasing use of mobile devices, having a mobile-friendly website is crucial. Ensure your site is responsive and provides an optimal user experience across different screen sizes.</p><h3>Content Marketing and Blogging</h3><p>Content marketing is an effective strategy to drive traffic and establish your e-commerce brand as an authority in your niche. By creating high-quality, informative, and engaging content, you can attract and retain visitors. Here are a few content marketing tips:</p><h4>Start a Blog</h4><p>Launching a blog on your e-commerce website allows you to provide valuable information, product reviews, tutorials, and industry insights. This not only attracts organic traffic but also helps build trust and credibility with your audience.</p><h4>Guest Blogging and Influencer Collaboration</h4><p>Collaborate with industry influencers and authoritative bloggers to create guest posts or co-authored content. This can help you reach new audiences, generate backlinks, and improve your overall SEO.</p><h4>User-Generated Content</h4><p>Encourage your customers to leave reviews, ratings, and testimonials. User-generated content not only helps with SEO but also builds trust and social proof.</p><h3>Technical SEO</h3><p>In addition to on-page optimization, technical SEO is essential to ensure that search engines can crawl and index your website efficiently. Some technical SEO aspects to consider include:</p><h4>Website Speed</h4><p>Optimize your website’s loading speed by minimizing code, compressing images, and utilizing caching techniques. A faster website improves user experience and helps with search rankings.</p><p><strong>Client-Side Rendering (CSR)</strong><br>Client-Side Rendering is a web development approach where the rendering of web pages occurs on the client-side, typically in the user’s web browser. With CSR, the initial HTML content is delivered to the browser, and then the JavaScript code takes over to fetch data from the server and dynamically render the page’s content. This approach provides a more interactive and dynamic user experience, as updates can be made without fully reloading the page. CSR is commonly used in modern e-commerce websites that heavily rely on JavaScript frameworks like React, Angular, or Vue.js. It allows for fast and responsive user interfaces, as well as enhanced interactivity, such as filtering products, adding items to the shopping cart without page refreshes, and real-time updates.</p><p><strong>Server-Side Rendering (SSR)</strong><br>Server-Side Rendering, on the other hand, is a web development approach where the web pages are rendered on the server and delivered to the client as complete HTML documents. When a user requests a page, the server dynamically generates the HTML content, including the data, and sends it to the client. SSR can be beneficial for e-commerce websites in several ways. It improves initial page load times since the server sends pre-rendered HTML to the client. This can be especially advantageous for search engine optimization (SEO) because search engine bots can easily crawl and index the pre-rendered HTML content.<br>Additionally, SSR allows for better performance on devices with lower processing power, as the server handles the rendering instead of relying heavily on the client’s device resources. This can enhance the user experience, particularly for visitors with slower internet connections or less powerful devices.</p><p><strong>Balancing CSR and SSR in E-Commerce:</strong><br>When it comes to e-commerce websites, finding the right balance between CSR and SSR depends on various factors, including the complexity of the user interface, performance requirements, and SEO considerations.<br>Many modern e-commerce platforms and frameworks offer hybrid approaches that combine CSR and SSR techniques. This allows for initial server-side rendering of the essential content to improve performance and SEO, while subsequent interactions and dynamic content updates are handled on the client-side using CSR techniques.<br>By using a hybrid approach, you can benefit from the initial performance gains and SEO advantages of SSR while still providing an interactive and dynamic user experience through CSR.</p><p>You can also install and configure a dynamic renderer (for example, <a href="https://developers.google.com/web/tools/puppeteer/get-started">Puppeteer</a> or <a href="https://prerender.io/">prerender.io</a>) to transform your content into static HTML that’s easier for crawlers to consume.</p><p>Here are some specific examples of how e-commerce businesses can use these methods:</p><ul><li>A retailer with a large catalog of products could use a hybrid approach to render the initial HTML for the product pages on the server, while allowing for dynamic content such as product reviews and recommendations to be updated on the client-side. This would help to ensure that the product pages load quickly for users, while also allowing for the dynamic content to be updated in real time.</li><li>An e-commerce business that sells products that are frequently updated could use a client-side rendered approach to ensure that the product pages are always up-to-date. This would help to improve the user experience and could also improve SEO, as search engines would be able to index the latest product information.</li><li>An e-commerce business that sells products that are not frequently updated could use a server-side pre-rendered approach to improve performance. This would allow the website to load more quickly for users, which could lead to increased conversions.</li></ul><h4>XML Sitemap</h4><p>Create an XML sitemap and submit it to search engines. This helps search engines discover and index your website’s pages more effectively.</p><p><a href="https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap">https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap</a></p><h4>Schema Markup</h4><p>Implement schema markup to provide additional context and structured data to search engines. This can improve your website’s visibility in search results and enable rich snippets for products, ratings, and other information.</p><p><a href="https://www.semrush.com/blog/what-is-schema-beginner-s-guide-to-structured-data/">https://www.semrush.com/blog/what-is-schema-beginner-s-guide-to-structured-data/</a></p><h3>Popular Tools</h3><p>Lighthouse</p><p><a href="https://developer.chrome.com/docs/lighthouse/seo/">https://developer.chrome.com/docs/lighthouse/seo/</a></p><p>Semrush</p><p><a href="https://www.semrush.com/">https://www.semrush.com/</a></p><h3>Conclusion</h3><p>Implementing effective e-commerce SEO optimization techniques can significantly enhance your online store’s visibility, increase organic traffic, and drive conversions. By conducting thorough keyword research, optimizing on-page elements, improving site architecture, creating valuable content, and taking care of technical SEO aspects, you can position your e-commerce business for success in the highly competitive online marketplace. Remember, SEO is an ongoing process, so continually monitor and adapt your strategies based on industry trends and search engine algorithm updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=add7dbbc18ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CommerceTools with Azure API Management]]></title>
            <link>https://medium.com/@amitnath/commercetools-with-azure-api-management-212b9e922817?source=rss-58c1ff4946a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/212b9e922817</guid>
            <dc:creator><![CDATA[Amit Nath]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 02:04:04 GMT</pubDate>
            <atom:updated>2023-02-11T02:04:04.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article I will explain how to use Azure API Management effectively to implement eCommerce APIs on top of <a href="https://commercetools.com/">CommerceTools</a>. How we can develop an backend API strategy that use both direct calls to Commercetools for simple calls and microservicce hosted APIs for more complex API calls. This will reduce the implementation time, yet supports the same features and CI/CD compatible too.</p><p>Those who are familiar with Commercetools and Azure APIM can directly jump to “CommerceTools with Azure API Management” section.</p><h3>Commercetools</h3><p>CommerceTools is a leader in Digital commerce. It is a leading commerce platform built on modern MACH principles (<a href="https://commercetools.com/mach-architecture/microservices"><strong>Microservice-based</strong></a>, <a href="https://commercetools.com/mach-architecture/api-commerce"><strong>API-first</strong></a>, <a href="https://commercetools.com/mach-architecture/cloud-native"><strong>Cloud-native</strong></a> and <a href="https://commercetools.com/mach-architecture/headless-commerce"><strong>Headless</strong></a>). They provide SaaS based subscription offering to their commerce APIs.</p><p>Combination of MACH and SaaS provides unrivalled levels of flexibility. You can do multiple things such as -</p><ol><li>Liberate the platform with best in breed independent customer experiences that are completely de-coupled from backend.</li><li>Use ready-made commerce building blocks to create or supplement your own infrastructure and run them at scale.</li><li>Free yourself from vendor lock-in by choosing only the third-party services you want and need.</li><li>Build a strong engineering team and culture around this ecosystem that can also benefit other sections of the organisation.</li></ol><h4>Using Commercetools</h4><p>CommerceTools provides eCommerce APIs to work with. It is a SaaS and subscription based platform. Means the underlying platform is managed by Commercetools and all data is stored inside their hosting.</p><p>We can call the APIs to perform typical commerce operations like add to cart, fetch product details, place order, register customer, apply promotions etc. There are also back-office interfaces to manage data.</p><p>We can use these APIs directly or built additional logic on top of them. However those additional logic will need to be developed, deployed and maintained by us outside Commercetools APIs. We can build micro-services using a suitable language SDK or write serverless functions.</p><h4>How to call Commercetools APIs?</h4><p>There are two options here. We can call <a href="https://docs.commercetools.com/api">APIs</a> directly or use one of their <a href="https://docs.commercetools.com/sdk/">SDKs</a> with our application.</p><p>Some typical examples of such APIs are -</p><ol><li>Product catalog related APIs allowing CRUD and search operations on products and categories.</li><li>Cart related APIs allowing create carts, add to cart, calculations etc.</li><li>Price and inventory APIs acting on product, store and channels.</li><li>Customer related APIs allowing CRUD operations on customer. Authentication, token management etc.</li><li>APIs for doing import/export sync etc with backend data.</li><li>GraphQL equivalents of these.</li></ol><p>An example API call to fetch product with id as id1 -</p><p>GET <a href="https://api.us-central1.gcp.commercetools.com/">https://api.us-central1.gcp.commercetools.com</a>/&lt;project-key&gt;/products/id1</p><h4>Why we need to customize API Functionalities</h4><p>No software is universal and cannot cater for all the requirements of a business without them doing any compromise. This leads to customisation of software features. CommerceTools is not an exception to this. Even if you might be able to do a lot of things by directly calling the APIs that are not opinionated, but there will always be gaps.</p><p>Example scenarios -</p><ol><li>External third party calls like payment gateway, tax calculation provider or address verification etc. We can make calls to make to do the external operations and store the final output into CommerceTools.</li><li>Additional validations on the fields.</li><li>Creating a separate and simpler request format for API consumers.</li><li>Implementing security and access management of the APIs with external providers like CIAM or IDAMs.</li><li>Performing complex transactions that requires multiple API calls to CommerceTools.</li></ol><h4>How to customize CommerceTools APIs?</h4><p>We need to have additional architectural building blocks on top of CommerceTools APIs to hold the additional logic and processing required. On the solution level those can be micro-services or serverless functions. We can use any widely adopted language or framework like spring boot, nodeJS, kotlin etc to build them. It can be AWS lambda functions, Azure functions or Google cloud functions when it comes to serverless.</p><h3>Azure API Management</h3><p>Azure API Management is a platform for managing APIs. It is made up of an API <em>gateway</em>, a <em>management plane</em>, and a <em>developer portal</em>. These components are Azure-hosted and fully managed by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*md-U0tKgLvOehSyw.png" /></figure><p>It is a good practice that all requests from client applications first reach an API gateway, which then forwards them to respective backend micro-services that call CommerceTools or directly to CommerceTools. The API gateway acts as a facade to the backend, allowing API us to abstract API implementations and evolve backend architecture without impacting API consumers. The gateway enables consistent configuration of routing, security, throttling, caching, and observability.</p><h4>Why API Gateway?</h4><p>When publishing APIs for consumption, it can be challenging to manage the communication between the API backend and the clients that consume them. There is a multitude of cross-cutting concerns such as authentication, authorization, throttling, caching, transformation, and monitoring. These concerns are valid regardless of whether the APIs are exposed to internal or external clients. The <a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/direct-client-to-microservice-communication-versus-the-api-gateway-pattern">API Gateway</a> pattern addresses these concerns.</p><p>Azure API gateway can serve as a front door to the commerce backend that consists of CommerceTools APIs and custom logic layer built on top of it. It can decouple clients from your commerce backend, adds an additional layer of security, and decreases the complexity of backend by removing the burden of handling cross cutting concerns.</p><h4>Using Azure API Management</h4><p>We can configure Azure API Management to create APIs that sit on top of</p><ol><li>CommerceTools APIs.</li><li>API endpoints from micro services that in turn calls CommerceTools or other services.</li><li>Serverless Azure Functions that in turn calls CommerceTools or other services.</li></ol><h3>CommerceTools with Azure API Management</h3><p>To implement commerce APIs with Azure APIM that is supported by CommerceTools backend and a set of micro services we need to first follow these generic steps.</p><h4>Configure commerce tools</h4><p>Sign up with commerce tools, create organisation, project.</p><h4>API Design</h4><p>Need to design APIs that will be required by the API consumers. Calls like add to cart, get product, customer etc.</p><p>These are some of the common API calls that are used in e-commerce applications, but the exact set of API calls can vary depending on the specific needs of the application and the platform it is built on.</p><p>1.<strong> Add to Cart:</strong> This API call allows a user to add a product to their shopping cart.</p><p>2.<strong> Get Product:</strong> This API call retrieves information about a specific product, such as its name, description, price, and image.</p><p>3. <strong>Get List of Products:</strong> This API call retrieves a list of all the products available in the catalog.</p><p>4. <strong>Get Cart:</strong> This API call retrieves the contents of a user’s shopping cart.</p><p>5. <strong>Update Cart:</strong> This API call allows a user to update the quantity of a product in their cart.</p><p>6. <strong>Remove from Cart:</strong> This API call allows a user to remove a product from their shopping cart.</p><p>7. <strong>Checkout: </strong>This API call initiates the checkout process, allowing a user to complete their purchase.</p><p>8. <strong>Order Confirmation:</strong> This API call confirms the details of an order, including the total cost, shipping address, and payment information.</p><p>9. <strong>Payment Processing:</strong> This API call processes a payment for an order.</p><p>10. <strong>Order Tracking:</strong> This API call allows a user to track the status of their order, including its shipping status and delivery date.</p><h4>Direct Vs Indirect Calls</h4><p>During the API design approach we need to decide which calls should be direct and which ones are complex should be calling a microservice instead.</p><p>Direct calls to Commercetools criteria could be —</p><ol><li>No request or response modification required.</li><li>No orchestration required.</li><li>Single call serves the purpose.</li><li>No custom logic required.</li><li>No external calls required.</li></ol><p>Everything else could use an APIs hosted by a microservice to implement.</p><p>Typical commerce APIs do the operations that we normally see in eCommerce websites like search, get products, customer, add to cart, checkout, payment etc.</p><h3>Implementation</h3><p>Its time to implement once we have designed APIs, decided on which ones going to be direct to Commercetools and which ones will need microservices.</p><p><strong>Step 1 — Implement microservices</strong></p><p>Example github project <a href="https://github.com/amitnath-lab/commercetools-spring-webflux-reactive-api">https://github.com/amitnath-lab/commercetools-spring-webflux-reactive-api</a></p><p>This essentially involves creating microservices using one of the market leading framework. These could be spring boot, kotlin or node.js based apps hosting APIs. Internally using one of the SDKs to interact with Commercetools when needed.</p><p>Full list of Commercetools SDKs available <a href="https://docs.commercetools.com/sdk/">here</a>.</p><p>They could be serverless apps or functions instead of microservices.</p><p><strong>Step 2— Azure APIM — create APIs</strong></p><p>First we need to create and Azure APIM instance. Full details on how to create APIM can be found <a href="https://learn.microsoft.com/en-us/azure/api-management/get-started-create-service-instance">here</a>. Its time to create APIs there once we have created an Azure APIM instance.</p><p>Create APIs in APIM. Detailed instructions on how to create APIs can be found <a href="https://learn.microsoft.com/en-us/azure/api-management/add-api-manually#create-an-api">here</a>. Ideally we should be doing this through a CI/CD process suing ARM templates which is explained later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e29596b276b674ef5e946b5ded756a9f/href">https://medium.com/media/e29596b276b674ef5e946b5ded756a9f/href</a></iframe><p><strong>Step 3— Azure APIM — create API operations</strong></p><p>We need to declare operations for the APIs we created, like add, delete, update etc. We can to define request and response details like request method, URL, templates, request and schema in the operations. However only request method and URL is mandatory and rest is up to you.</p><p>URL templates — These can help with requests that needs URL parameters like store, country, language etc. It is recommended to make their proper use when implementing a generic platform.</p><p><strong>Step 4— Azure APIM — create API policies</strong></p><p>Use appropriate policies to change API behavior through configuration using <em>policies</em>. Policies are a collection of statements that are run sequentially on the request or response of an API. You can do various things using policies like:</p><ol><li>Format conversion from XML to JSON</li><li>Rate limiting.</li><li>Request filtering.</li><li>URL re-writing.</li><li>Caching.</li><li>Token management.</li></ol><p>For a complete list, see <a href="https://learn.microsoft.com/en-us/azure/api-management/api-management-policies">API Management policy reference</a>.</p><p>Below is a sample ARM template with bare minimums.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a481b09bb573bac7df6742f270058a0/href">https://medium.com/media/1a481b09bb573bac7df6742f270058a0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=212b9e922817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure API Management CI/CD with ARM templates]]></title>
            <link>https://medium.com/@amitnath/azure-api-management-ci-cd-with-arm-templates-73934685d934?source=rss-58c1ff4946a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/73934685d934</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[azure-arm]]></category>
            <category><![CDATA[azure-api-management]]></category>
            <dc:creator><![CDATA[Amit Nath]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 22:31:09 GMT</pubDate>
            <atom:updated>2023-01-19T19:29:59.267Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Azure API Management is a fully managed service that enables organisations to publish, secure, and monitor APIs. It helps businesses expose their backend services and data to external developers, partners, and customers in a secure and scalable manner.</p><p>One of the key benefits of Azure API Management is the ability to implement a continuous integration and continuous deployment (CI/CD) workflow using ARM templates. ARM templates are a declarative syntax for defining Azure resources, and they allow you to automate the deployment of your API Management service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*kFByk_Ycw-1LMVAPu8Xb4A.png" /></figure><p>By using ARM templates and Azure DevOps, you can automate the deployment of your API Management service and ensure that it is consistently and reliably deployed across all of your environments. This helps you to reduce the time and effort required to manage your API Management service, and it enables you to focus on delivering value to your customers.</p><h3>What is Azure ARM templates</h3><p>Azure Resource Manager (ARM) templates are a declarative syntax for defining Azure resources. They allow you to specify the resources that you want to deploy to Azure, as well as the properties and settings for those resources. ARM templates are written in JSON, and they can be used to deploy a wide variety of Azure resources, including virtual machines, storage accounts, and Azure Functions.</p><p>One of the key benefits of using ARM templates is that they enable you to automate the deployment of your Azure resources. You can use ARM templates to define your desired infrastructure as code, and then use tools such as Azure DevOps to deploy that infrastructure in a consistent and reliable manner. This helps you to save time and effort, and it enables you to deploy your resources in a predictable and repeatable way.</p><p>In addition to deploying resources, ARM templates can also be used to update existing resources and delete resources that are no longer needed. They can also be parameterised, which means that you can use the same template to deploy resources with different configurations or settings.</p><p>Overall, ARM templates are a powerful and flexible tool for deploying and managing Azure resources, and they are an essential part of many Azure CI/CD workflows.</p><h3>Why CI/CD required for API gateway</h3><p>Continuous integration and continuous deployment (CI/CD) is a software development practice that involves constantly integrating new code changes into a codebase and automatically deploying those changes to production. It helps organizations to deliver new features and updates to their customers faster and more reliably.</p><p>In the context of an API gateway, CI/CD can be particularly useful for the following reasons:</p><ol><li>Continuous integration allows teams to detect and fix integration issues early on, reducing the risk of costly bugs and downtime.</li><li>Continuous deployment automates the process of releasing new features and updates to the API gateway, reducing the time and effort required to manage the gateway.</li><li>By automating the deployment process, CI/CD can help to ensure that the API gateway is consistently and reliably deployed across all environments, including development, staging, and production.</li><li>CI/CD can also help organisations to adopt a culture of continuous improvement, enabling them to rapidly iterate on their API gateway and respond to changing customer needs.</li></ol><p>Overall, CI/CD is an essential practice for organisations that want to deliver high-quality API gateways and rapidly respond to changing business needs.</p><h3>Terraform Vs Azure ARM</h3><p>Terraform and Azure Resource Manager (ARM) templates are both tools for deploying and managing infrastructure as code. They both enable you to define your infrastructure in a declarative syntax, and then use that syntax to automate the deployment and management of your resources.</p><p>There are a few key differences between Terraform and ARM templates:</p><ol><li>Language: Terraform uses its own domain-specific language (DSL) for defining infrastructure, while ARM templates use JSON. Some people find the Terraform DSL easier to read and write, while others prefer the more familiar syntax of JSON.</li><li>Supported platforms: Terraform is a multi-cloud tool that can be used to manage infrastructure on a wide variety of platforms, including Azure, AWS, and Google Cloud. ARM templates are specific to Azure.</li><li>Resource management: Terraform uses a custom state management system to keep track of the resources it has deployed, while ARM templates use Azure Resource Manager, which is a native Azure service for managing resources.</li><li>Ecosystem: Terraform has a large and active community, with many third-party plugins and integrations available. ARM templates are more tightly integrated with Azure and the Azure ecosystem, and they have native support for Azure features such as role-based access control and tagging.</li></ol><p>Ultimately, the choice between Terraform and ARM templates will depend on your specific needs and requirements. Both tools are powerful and capable of automating the deployment and management of Azure resources, so it’s worth considering which one is the best fit for your use case.</p><h3>Steps</h3><p>Here are the steps for implementing a continuous integration and continuous deployment (CI/CD) workflow for Azure API Management using ARM templates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*7lcW7_iat-piRP8znKnOJA.png" /></figure><ol><li>Create an Azure DevOps project and set up a Git repository for your ARM templates.</li><li>Write your ARM templates for deploying your API Management service and its associated resources, such as APIs, policies, and products. You can use Visual Studio Code and the Azure Resource Manager extension to help you write and validate your templates. I have added a sample template in the next section.</li><li>Set up a build pipeline in Azure DevOps to build and deploy your ARM templates. You can use tasks such as Azure Resource Group Deployment and Azure Resource Group Template Deployment to deploy your templates to Azure.</li><li>Set up a release pipeline in Azure DevOps to automate the release of your API Management service to different environments, such as development, staging, and production. You can use tasks such as Azure API Management Deployment and Azure API Management Import/Export to deploy your APIs and policies to Azure API Management.</li><li>Test your release pipeline to ensure that it is working correctly and that your API Management service is being deployed as expected.</li><li>Monitor your API Management service in production to ensure that it is performing as expected and to identify and resolve any issues that arise.</li></ol><p>By following these steps, you can set up a CI/CD workflow for Azure API Management using ARM templates that helps you to automate the deployment of your API Management service and ensure that it is consistently and reliably deployed across all of your environments.</p><h3>Sample ARM Template</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46f853f286b5d0de8dd6fd4c8ccbfed1/href">https://medium.com/media/46f853f286b5d0de8dd6fd4c8ccbfed1/href</a></iframe><p>This template uses the Azure Resource Manager (ARM) deployment model to create an API Management service with the specified name, location, SKU, and capacity. It also creates an API named “echoapi” with an operation named “echo”. Additionally, the template creates a policy named “echoapi_policy” and a product named “echoapi_product” that includes the “echoapi” API and the “echoapi_policy” policy.<br>Please note that this is a basic template, you may need to adjust it to suit your specific requirements.</p><h3>Conclusion</h3><p>Implementing a continuous integration and continuous deployment (CI/CD) workflow for Azure API Management using ARM templates can be particularly beneficial for projects that have the following characteristics:</p><ol><li>Large number of APIs: If you have a large number of APIs that need to be managed, CI/CD can help you automate the process of releasing and updating your APIs, reducing the time and effort required to manage them.</li><li>Frequent updates: If you need to make frequent updates to your APIs, CI/CD can help you deploy those updates in a consistent and reliable manner.</li><li>Multiple environments: If you have multiple environments, such as development, staging, and production, CI/CD can help you automate the deployment of your APIs across those environments.</li><li>Complex dependencies: If your APIs have complex dependencies, such as on other APIs or external services, CI/CD can help you manage those dependencies and ensure that your APIs are deployed correctly.</li></ol><p>Overall, projects that have a large number of APIs, need to make frequent updates, have multiple environments, or have complex dependencies are good candidates for adopting Azure API Management CI/CD with ARM templates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73934685d934" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Webflux with Commercetools]]></title>
            <link>https://medium.com/@amitnath/spring-webflux-with-commercetools-f204dc449399?source=rss-58c1ff4946a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f204dc449399</guid>
            <category><![CDATA[reactor]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[webflux]]></category>
            <category><![CDATA[commercetools]]></category>
            <category><![CDATA[reactor-project]]></category>
            <dc:creator><![CDATA[Amit Nath]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 16:58:58 GMT</pubDate>
            <atom:updated>2022-11-08T18:37:51.624Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this blog, we will understand how to use <strong>Spring Webflux</strong> with <strong>Commercetools</strong> SDK to create commerce REST APIs that are non-blocking in nature due to use of reactive programming, better preforming while handling concurrent traffic load and potentially can result better utilization of system resources.</p><p>Spring Boot is popular Java framework for writing Microservices. It provides various extension projects under Spring Cloud to build full stack Microservices. With Spring Boot, your microservices can start small and iterate fast. These microservice are scalable and extensible by framework design. It also support various ways to deploying, monitoring and scaling services with ready to use products and frameworks from different cloud providers.</p><h3>Commercetools</h3><p>This article is intended for reader who are already aware of what CommerceTools is.</p><p>However, for a quick overview —</p><p>Commercetools is among the world’s leading platforms for B2C (Business-to-Consumer) and B2B (Business-to-Business) commerce. It offers a true cloud-based, headless commerce platform that provides the building blocks to compose your own e-commerce backend. Different commerce modules like product, order, customer, checkout are exposed via REST and graphQL APIs.</p><p>It also provides SDKs in different language to build your own applications over it. One of them is <a href="https://docs.commercetools.com/sdk/jvm-sdk">java SDK</a> which is widely used by application developers to build REST API based spring microservices.</p><h3>Issues with the traditional REST APIs</h3><p>REST APIs, specially the ones that are exposed to internet and supposed to serve high traffic are vulnerable to back pressure and thread blocking operations.</p><p>E-commerce APIs even though highly elastic and horizontally scalable, has limits of underlying infraustructure. Specially if it needs to call another service, downstream, third-party or database. Thread pool exhaustion, hitting capacity of the downstream are common phenomenons in the real world with high traffic mircoservices. Specially during peak times like black friday, singles day or flash sales etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*henIGrBcWZ6Bdfh96N2Npw.png" /><figcaption>Blocking threads in normal spring MVC</figcaption></figure><p>Below are some of the issues with the traditional REST APIs,</p><p><strong>Blocking and Synchronous →</strong> The request is blocking and synchronous. The request thread will be waiting for any blocking I/O and the thread is not freed to return the response to the caller until the I/O wait is over.<br><strong>Thread per request → </strong>The web container uses a thread-per-request model. This limits the number of concurrent requests to handle. Beyond certain requests, the container queues the requests that eventually impact the performance of the APIs.<br><strong>Limitations to handle high concurrent users → </strong>As the web container uses a thread-per-request model, we cannot handle high concurrent requests.<br><strong>No better utilization of system resources →</strong> The threads will be blocking for I/O and sitting idle. But, the web container cannot accept more requests. During this scenario, we are not able to utilize the system resources efficiently.<br><strong>No backpressure support →</strong> We cannot apply backpressure from the client to the server. If there is a sudden surge of requests the server outages may happen. After that, the application will not be accessible to the users. If we have backpressure support, the application should sustain during the heavy load rather than the unavailability.</p><h3>Reactive Programming with Spring WebFlux</h3><p>Spring WebFlux provides Reactive Programming to web applications. The asynchronous and non-blocking nature of Reactive design improves performance and memory usage.</p><p>Due to the non-blocking nature of Reactive Programming, the server doesn’t send the complete stream at once. It can push the data concurrently as soon as it is available. Thus, the client waits less time to receive and process the events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*k1MPXJNIzDLAol5qNdvPQA.png" /><figcaption>Non-blocking threads with Spring Webflux using reactor core</figcaption></figure><p>In a non-blocking system, all the incoming requests are accompanied by an event handler and a callback. The request thread delegates the incoming request to a thread pool that manages a pretty small number of threads. Then the thread pool delegates the request to its handler function and gets available to process the next incoming requests from the request thread.</p><p>When the handler function completes its process, one of the threads from the pool fetches the response and passes it to the callback function. Thus the threads in a non-blocking system never go into the waiting state. This increases the productivity and the performance of the application.</p><h3>Using WebFlux with Commerce Tools Java SDK</h3><p>It is very easy to use CommerceTools java sdk within a spring boot app to build microservices that interact with CommerceTools.</p><p>Below are the steps needed to accomplish the job. You can also check my github project also in this <a href="https://github.com/amitnath-lab/commercetools-spring-webflux-reactive-api">link</a>.</p><p><strong>Step 1 — Create the micro service</strong></p><p>Generate a spring boot project from <a href="https://start.spring.io/">https://start.spring.io/</a> with your choice of build tool. Add “Spring Reactive Web” as a dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f592RtABfV5ezptpCAcBVw.png" /></figure><p><strong>Step 2 — Add dependencies</strong></p><p>Add the required dependencies for Spring webflux and commercetools inside build.gradle file of the generated project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e57ccb10b5ad8ed907421971eb90272/href">https://medium.com/media/8e57ccb10b5ad8ed907421971eb90272/href</a></iframe><p><strong>Step 3 — CommerceTools client</strong></p><p>First we need create a CommerceTools client using its SDK.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ee42727ccb5c5879268b8a058469df5/href">https://medium.com/media/5ee42727ccb5c5879268b8a058469df5/href</a></iframe><p><strong>Step 4 — Define the service</strong></p><p>Define a service that will do some operation on CommerceTools using the client. For demo purpose, I have used a service to get category by key and id. Note that the service is returning a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html">CompletableFuture</a>. Reactor core APIs are compatible with CompletableFuture and we will later create a Mono publisher out of it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73230f4343c3d5b1fa1e09d321d28584/href">https://medium.com/media/73230f4343c3d5b1fa1e09d321d28584/href</a></iframe><p><strong>Step 5 — Define the Rest Controller Endpoints</strong></p><p>Create the endpoints in the controller. Webflux is compatible with web MVC <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-controller">annotations</a>. So we can create annotated controllers same as any other spring boot rest API. It publishes a reactive stream of a single resource. We wrap a single <em>Category</em> resource in a <em>Mono</em> because we return at most one category.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d26eabfaf4c1a66705e0235b39d17e2a/href">https://medium.com/media/d26eabfaf4c1a66705e0235b39d17e2a/href</a></iframe><p><strong>Step 5 — Run and test</strong></p><p>Run the standard spring boot commands to run this project.</p><p>gradle build &amp;&amp; gradle bootRun</p><p>Then use curl to call the API endpoint</p><pre>curl --location --request GET &#39;<a href="http://localhost:8080/category/1b96027c-8bcf-4410-9188-6563c72e2a4a&#39;">http://localhost:8080/category/{categoryID}&#39;</a> </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f204dc449399" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>