<?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 Yusuf Azaz on Medium]]></title>
        <description><![CDATA[Stories by Yusuf Azaz on Medium]]></description>
        <link>https://medium.com/@yusuf-azaz?source=rss-c664523b63a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cyxaM4kCUMESFstaJyDh3w.jpeg</url>
            <title>Stories by Yusuf Azaz on Medium</title>
            <link>https://medium.com/@yusuf-azaz?source=rss-c664523b63a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:13:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yusuf-azaz/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[Making Enterprise APIs Available as MCP Tools: A Practical Guide]]></title>
            <link>https://yusuf-azaz.medium.com/making-enterprise-apis-available-as-mcp-tools-a-practical-guide-6d812dddf930?source=rss-c664523b63a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d812dddf930</guid>
            <category><![CDATA[agentic-applications]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Yusuf Azaz]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 22:17:28 GMT</pubDate>
            <atom:updated>2025-12-11T22:17:28.996Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Model Context Protocol (MCP) is reshaping the way AI agents communicate with external systems. Rather than hard-coding API interactions directly into your prompt engineering or scattering integration logic across your application, MCP introduces a unified, standards-driven interface that enables any AI model — Claude, GPT, or otherwise — to automatically discover, understand, and invoke your services in a controlled and dependable way.</p><p>In this guide, we’ll walk through a practical, enterprise-focused example: turning an existing data API platform into a suite of MCP-enabled tools. Along the way, you’ll see how to:</p><ul><li>Design an MCP server that acts as a proxy layer in front of internal/enterprise APIs</li><li>Implement service-level authentication, including handling unique API keys per backend service</li><li>Publish your MCP server over HTTP for seamless client connectivity</li><li>Build Python clients that interact with your tools as first-class MCP resources</li><li>Integrate everything into agent frameworks like LangChain to power automated, intelligent workflows</li></ul><p>Let’s get started. You can find the code on <a href="https://github.com/yusufazaz/mcp_blog.git">github</a>.</p><p><strong>The Architecture: From Enterprise API to MCP Tools</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69F4EJbQJGhZFOwsfYKU0A.png" /><figcaption>MCP Architecture</figcaption></figure><p><strong>Key components:</strong></p><ul><li><strong>External Services</strong>: Your actual APIs (in this example, tax data endpoints)</li><li><strong>MCP Server</strong>: FastMCP instance that wraps your APIs as tools with standardized schemas</li><li><strong>Authentication</strong>: Service-specific API keys managed in one place</li><li><strong>HTTP Transport</strong>: Uvicorn server exposing the MCP protocol at <strong><em>/mcp</em></strong></li><li><strong>Clients</strong>: Python applications (including LangChain agents) that discover and call tools</li></ul><p><strong>Step 1: Structure Your MCP Server</strong></p><p>Begin by creating a straightforward main.py file that initializes your FastMCP server and wires up all the tools exposed by different tax services:</p><pre># main.py<br>from fastmcp import FastMCP<br>from individual_tax_tools import register_individual_tools<br>from business_tax_tools import register_business_tools<br>from notice_tools import register_notice_tools<br><br># Create MCP server instance<br>mcp = FastMCP(&quot;Tax Data MCP Server&quot;)<br><br># Register all tools<br>register_individual_tools(mcp)<br>register_business_tools(mcp)<br>register_notice_tools(mcp)<br><br>if __name__ == &quot;__main__&quot;:<br>    mcp.run()</pre><p>Each domain — individual tax, business tax, and notices — is encapsulated in its own module, ensuring clean separation of responsibilities and making the server easier to extend and maintain.</p><p><strong>Step 2: Define Service-Specific Tools</strong></p><p>Each tax domain exposes its own set of MCP tools. To keep the code organized and scalable, you define a registration function per service and decorate async methods to expose them through MCP:</p><pre># individual_tax_tools.py<br>import httpx<br>from fastmcp import FastMCP<br>from auth import get_individual_headers<br><br>INDIVIDUAL_RETURNS_API_BASE_URL = &quot;https://myreturns.mock.it&quot;<br><br>def register_individual_tools(mcp: FastMCP):<br>    &quot;&quot;&quot;Register MCP tools for individual tax returns.&quot;&quot;&quot;<br>    <br>    @mcp.tool()<br>    async def get_individual_1040_return(tax_id: str, tax_year: int) -&gt; dict:<br>        &quot;&quot;&quot;Gets the 1040 tax returns submitted to the IRS.&quot;&quot;&quot;<br>        async with httpx.AsyncClient(headers=get_individual_headers()) as client:<br>            try:<br>                response = await client.get(<br>                    f&quot;{INDIVIDUAL_RETURNS_API_BASE_URL}/individual/returns/{tax_id}/{tax_year}&quot;<br>                )<br>                response.raise_for_status()<br>                return response.json()<br>            except httpx.HTTPStatusError as e:<br>                return {&quot;error&quot;: f&quot;HTTP {e.response.status_code}: {e.response.text}&quot;}<br>            except httpx.RequestError as e:<br>                return {&quot;error&quot;: f&quot;Request failed: {e}&quot;}</pre><p><strong>What this pattern gives you</strong></p><p>Clean separation of domains: Each service — individual, business, notices — owns its own tool registration.</p><ul><li>Simple tool definition: Async functions decorated with <em>@mcp.tool()</em> are automatically surfaced to any MCP-compatible client.</li><li>Automatic parameter exposure: Type hints become part of the tool schema.</li><li>Built-in documentation: Docstrings become the official tool descriptions.</li><li>Consistent error reporting: Tools return structured JSON responses rather than raising exceptions.</li><li>Service-specific authentication: Each API uses its own header injector, keeping credentials isolated and secure.</li></ul><p>This structure makes it easy to onboard new services, add new endpoints, and maintain clean boundaries between tax domains.</p><p><strong>Step 3: Add Service-Specific Authentication</strong></p><p>One of the major advantages of designing your MCP server this way is the ability to use different API keys for each backend service — all managed through a single, centralized configuration layer.</p><pre># auth.py<br>import os<br>from typing import Optional<br><br>class AuthConfig:<br>    &quot;&quot;&quot;Configuration for service-specific API key authentication.&quot;&quot;&quot;<br>    <br>    def __init__(<br>        self,<br>        individual_api_key: Optional[str] = None,<br>        business_api_key: Optional[str] = None,<br>        notice_api_key: Optional[str] = None,<br>        api_key_header: str = &quot;X-API-Key&quot;,<br>    ):<br>        # Load from environment variables<br>        self.individual_api_key = individual_api_key or os.getenv(&quot;INDIVIDUAL_API_KEY&quot;)<br>        self.business_api_key = business_api_key or os.getenv(&quot;BUSINESS_API_KEY&quot;)<br>        self.notice_api_key = notice_api_key or os.getenv(&quot;NOTICE_API_KEY&quot;)<br>        self.api_key_header = api_key_header<br>    <br>    def get_individual_headers(self) -&gt; dict:<br>        if self.individual_api_key:<br>            return {self.api_key_header: self.individual_api_key}<br>        return {}<br>    <br>    def get_business_headers(self) -&gt; dict:<br>        if self.business_api_key:<br>            return {self.api_key_header: self.business_api_key}<br>        return {}<br>    <br>    def get_notice_headers(self) -&gt; dict:<br>        if self.notice_api_key:<br>            return {self.api_key_header: self.notice_api_key}<br>        return {}<br><br># Global config (can be replaced at runtime)<br>_auth_config = AuthConfig()<br><br>def get_individual_headers() -&gt; dict:<br>    return _auth_config.get_individual_headers()<br><br>def get_business_headers() -&gt; dict:<br>    return _auth_config.get_business_headers()<br><br>def get_notice_headers() -&gt; dict:<br>    return _auth_config.get_notice_headers()</pre><p>This architecture keeps credentials outside your codebase, enforces an authentication boundary per service, and eliminates noisy conditionals or global shared API keys. Each tool simply asks for the headers it needs, while the authentication logic remains isolated and easy to update.</p><p><strong>Step 4: Expose Your MCP Server Over HTTP</strong></p><p>To allow clients to connect and interact with your MCP tools, you can wrap the FastMCP server in an HTTP application using Starlette/ASGI and run it with Uvicorn:</p><pre># server_http.py<br>from main import mcp<br><br># Call the http_app factory to get the started ASGI app<br>app = mcp.http_app()</pre><pre>#Start the server:<br>uvicorn server_http:app --reload --port 8000</pre><p>It speaks the MCP protocol (JSON-RPC over HTTP), allowing any MCP-compatible client to discover tools and make requests programmatically. This setup decouples your tool definitions from the transport layer, making it easy to switch to HTTPS, deploy behind a reverse proxy, or scale horizontally.</p><p><strong>Step 5: Build a Python Client</strong></p><p>Clients use the official <strong><em>fastmcp</em></strong> Python library to discover and invoke tools:</p><pre># client_example.py<br>import asyncio<br>from fastmcp.client.client import Client<br><br>async def main():<br>    # Connect to MCP server<br>    async with Client(&quot;http://localhost:8000/mcp&quot;) as client:<br>        # List all available tools<br>        tools = await client.list_tools()<br>        print(f&quot;Available tools: {len(tools)}&quot;)<br>        for tool in tools:<br>            print(f&quot;  - {tool.name}: {tool.description}&quot;)<br>        <br>        # Call a tool<br>        result = await client.call_tool(<br>            &quot;get_individual_1040_return&quot;,<br>            {&quot;tax_id&quot;: &quot;123456789&quot;, &quot;tax_year&quot;: 2023}<br>        )<br>        print(f&quot;Result: {result}&quot;)<br><br>asyncio.run(main())</pre><p><strong>Step 6: Integrate MCP Tools with LangChain Agents</strong></p><p>CP tools integrate seamlessly with LangChain agents, allowing LLMs to invoke APIs dynamically without embedding endpoint logic in prompts. Here’s an example of wrapping an MCP tool for use in LangChain:</p><pre>from langchain.tools import Tool<br><br>def lc_get_1040(tax_id: str, tax_year: int):<br>    &quot;&quot;&quot;Sync wrapper for LangChain.&quot;&quot;&quot;<br>    result = asyncio.run(<br>        client.call_tool(&quot;get_individual_1040_return&quot;, {<br>            &quot;tax_id&quot;: tax_id,<br>            &quot;tax_year&quot;: tax_year<br>        })<br>    )<br>    return json.dumps(result, indent=2)<br><br># Create LangChain tool<br>lc_tool = Tool.from_func(<br>    lc_get_1040,<br>    name=&quot;get_individual_1040_return&quot;,<br>    description=&quot;Get 1040 return for a given TIN and tax year&quot;<br>)<br><br># Use in an agent<br>from langchain.agents import initialize_agent, AgentType<br>from langchain_openai import ChatOpenAI<br><br>llm = ChatOpenAI(model=&quot;gpt-4&quot;)<br>tools = [lc_tool]  # Add more MCP tools here<br><br>agent = initialize_agent(<br>    tools,<br>    llm,<br>    agent_type=AgentType.OPENAI_FUNCTIONS,<br>    verbose=True<br>)<br><br>response = agent.run(&quot;Find the 1040 return for TIN 123456789 filed in 2023&quot;)</pre><p><strong>Advantage of using Langchain</strong></p><ul><li>No hardcoded endpoints: Agents discover and call MCP tools dynamically.</li><li>Structured input/output: Tools enforce typed parameters and consistent JSON responses.</li><li>Composable workflows: Combine multiple MCP tools for multi-step agentic tasks.</li></ul><p>This approach empowers your LLMs to safely interact with enterprise APIs while keeping your integration layer modular and maintainable.</p><h3><strong>Conclusion</strong></h3><p>Transforming your enterprise APIs into MCP tools opens a powerful pathway for AI agents to access and interact with your services in a controlled, standardized manner. The approach follows a clear pattern:</p><p>Structure your MCP server to register and organize tools by domain</p><p>Expose the server over HTTP using FastMCP for seamless client connectivity</p><p>Connect clients — whether Python scripts, LangChain agents, or other MCP-compatible frameworks</p><p>Scale effortlessly by adding new tools without modifying existing client code</p><p>By adopting this methodology, you separate concerns, enhance security, and make your enterprise APIs fully discoverable and usable by any AI agent that understands the MCP protocol, enabling autonomous, agentic workflows that drive business outcomes efficiently.</p><p><em>Note: This example is intended for educational purposes and demonstrates a simplified MCP implementation. For production use, additional considerations — such as robust authentication, rate limiting, logging, monitoring, security audits, error handling, and scalability optimizations — must be addressed before deploying in a real enterprise environment.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d812dddf930" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Observability Insight Agent with Auto-Rollback on Kubernetes]]></title>
            <link>https://yusuf-azaz.medium.com/building-an-ai-powered-observability-insight-agent-with-auto-rollback-on-kubernetes-0373e715c94c?source=rss-c664523b63a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0373e715c94c</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Yusuf Azaz]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 22:52:37 GMT</pubDate>
            <atom:updated>2025-10-11T22:52:37.421Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Leveraging AI for Smarter Incident Response and Automated Rollbacks in Cloud-Native Environments</strong></p><p>Modern cloud-native architectures, built primarily around <strong>microservices</strong> and orchestrated via <strong>Kubernetes clusters</strong>, present significant operational challenges. These systems, frequently scaling into the hundreds of individual services, are constantly running and dynamically changing. As a direct result, they generate an <strong>enormous, continuous torrent of telemetry data</strong> — specifically, mountains of performance <strong>metrics, detailed application logs, and crucial Kubernetes events</strong> — every single second. The process of wading through this complex data deluge to accurately <strong>detect subtle anomalies</strong>, perform rapid <strong>incident triaging</strong>, and, most critically, make the high-stakes decision of whether to <strong>rollback a problematic deployment</strong> to a known good state, becomes an incredibly <strong>daunting and time-consuming manual task</strong> for operations teams.</p><p>This inevitable complexity begs a fundamental question: What if we could effectively <strong>leverage the analytical power of Artificial Intelligence</strong> to cut through the noise? Specifically, could an AI system be designed to autonomously <strong>analyze emerging incidents</strong>, instantly <strong>correlate</strong> them with the exact <strong>deployment activities and Kubernetes events</strong> that preceded the failure, and then possess the intelligence to <strong>trigger automatic rollbacks</strong> only when the confidence score and predetermined conditions are met?</p><p>In this comprehensive post, I will thoroughly walk you through the complete process of designing and building a highly autonomous <strong>Observability Insight Agent</strong> that performs precisely these actions. The implementation leverages a powerful combination of <strong>Python</strong> for the agent’s core logic, <strong>OpenAI’s reasoning capabilities</strong>, and deep integration with modern DevOps tools, including <strong>New Relic</strong> for data ingestion, <strong>ArgoCD</strong> and <strong>Helm</strong> for deployment automation, and <strong>Slack</strong> for timely notification and human-in-the-loop controls.</p><p>You can access all the foundational source code and necessary configurations directly on <a href="https://github.com/yusufazaz/observability-agent.git">GitHub</a>.</p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXhGMANZvuC6yWdQQcGixg.png" /></figure><p>Our Observability Insight Agent consists of:</p><p>· <strong>Alert Ingestion</strong>: Receives alerts (e.g., from Prometheus, NewRelic, or custom monitoring).</p><p>· <strong>Observability Context Collection</strong>: Gathers metrics, logs, recent deployments, and Kubernetes events.</p><p>· <strong>AI Triage</strong>: Uses OpenAI GPT-5 to analyze the context and output root cause, remediation, and confidence score.</p><p>· <strong>Decision Engine</strong>: Triggers automatic rollback if a recent deployment is correlated and confidence is high.</p><p>· <strong>Slack Integration</strong>: Posts actionable triage summaries and rollback approval requests.</p><h3><strong>Tech Stack</strong></h3><ul><li><strong>Python 3.11</strong>: Flask-based web service</li><li><strong>OpenAI GPT-5</strong>: AI-based triage engine</li><li><strong>NewRelic GraphQL API</strong>: Metrics and log collection</li><li><strong>ArgoCD API</strong>: Deployment history and rollback</li><li><strong>Kubernetes Python Client</strong>: Event collection and cluster interaction</li><li><strong>Slack Webhook</strong>: Notification &amp; approvals</li><li><strong>Docker &amp; Helm</strong>: Containerization and deployment</li><li><strong>GitLab CI/CD</strong>: Pipeline automation</li></ul><p><strong>Step 1: Observability Data Collection</strong></p><p>We gather context from:</p><ol><li><strong>Metrics</strong>: CPU and memory utilization over the past 30 minutes from NewRelic.</li><li><strong>Logs</strong>: Recent logs from the same period.</li><li><strong>Deployments</strong>: Recent ArgoCD deployments (within the last hour).</li><li><strong>Kubernetes Events</strong>: Recent cluster events in the relevant namespace.</li></ol><pre>def get_recent_metrics(service_name):<br>    query = f&quot;FROM Metric SELECT average(cpu.percent), average(memory.percent) WHERE appName=&#39;{service_name}&#39; SINCE 30 minutes ago&quot;<br>    return query_newrelic(query)<br><br>def get_recent_logs(service_name):<br>    query = f&quot;FROM Log SELECT message, timestamp WHERE appName=&#39;{service_name}&#39; SINCE 30 minutes ago LIMIT 50&quot;<br>    return query_newrelic(query)<br><br>def get_recent_deployments(app_name, since_minutes=60):<br>    # Fetch from ArgoCD API and filter by deployedAt timestamp<br>    ...<br><br>def get_recent_k8s_events(namespace=&quot;default&quot;, since_minutes=60):<br>    # Use Kubernetes client to fetch recent events<br>    ...</pre><p><strong>Step 2: AI Triage with GPT-5</strong></p><p>The AI engine analyzes all the context and outputs a structured JSON with:</p><ul><li>root_cause</li><li>deployment_related (true/false)</li><li>remediation</li><li>confidence (1–10)</li></ul><pre>def analyze_alert(alert, metrics, logs, deployments, events):<br>    context = f&quot;&quot;&quot;<br>    Alert: {alert}<br>    Metrics: {metrics}<br>    Logs: {logs}<br>    Deployments: {deployments}<br>    Kubernetes Events: {events}<br>    &quot;&quot;&quot;<br>    prompt = f&quot;&quot;&quot;<br>    You are an AI Observability Agent.<br>    Analyze the context and output JSON with: root_cause, deployment_related, remediation, confidence<br>    Context:<br>    {context}<br>    &quot;&quot;&quot;<br>    response = client_ai.chat.completions.create(<br>        model=&quot;gpt-5&quot;,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}]<br>    )<br>    return json.loads(response.choices[0].message.content)</pre><p><strong>Step 3: Auto-Rollback Logic</strong></p><p>We only attempt rollback if <strong>confidence is higher than the configured threshold</strong> and there’s a <strong>recent deployment</strong>:</p><pre>if confidence &gt;= CONFIDENCE_THRESHOLD:<br>    rollback_result = attempt_auto_rollback(<br>        app_name=entity,<br>        problematic_revision=recent_deploy.get(&quot;revision&quot;),<br>        triage_summary=root_cause,<br>        confidence=confidence,<br>        deployed_at_str=recent_deploy.get(&quot;deployedAt&quot;),<br>    )<br>else:<br>    post_slack_summary(entity, triage)<br></pre><p><strong>Rollback Conditions</strong></p><ol><li>Recent deployment exists (within configurable window, e.g., 60 mins).</li><li>Confidence exceeds threshold (e.g., ≥ 8.0).</li><li>If approval workflow is enabled, Slack posts an <strong>Approve/Deny</strong> message; otherwise, rollback executes automatically.</li></ol><p><strong>Step 4: Slack Integration</strong></p><p>We notify operators with a clear summary:</p><pre>def post_slack_summary(app_name, triage):<br>    summary = (<br>        f&quot;*🔍 AI Triage Summary*\n&quot;<br>        f&quot;App: `{app_name}`\n&quot;<br>        f&quot;Root Cause: {triage[&#39;root_cause&#39;]}\n&quot;<br>        f&quot;Deployment Related: {triage[&#39;deployment_related&#39;]}\n&quot;<br>        f&quot;Remediation: {triage[&#39;remediation&#39;]}\n&quot;<br>        f&quot;Confidence: {triage[&#39;confidence&#39;]}&quot;<br>    )<br>    requests.post(SLACK_WEBHOOK, json={&quot;text&quot;: summary})</pre><p><strong>Step 5: Pipeline &amp; Helm Deployment</strong></p><p>We package the application as a Docker container and deploy it using Helm. The <strong>GitLab CI/CD pipeline</strong> automates this:</p><pre>stages:<br>  - lint<br>  - test<br>  - dockerize<br>  - deploy<br><br>docker_build:<br>  stage: dockerize<br>  script:<br>    - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA .<br>    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA<br><br>deploy:<br>  stage: deploy<br>  script:<br>    - helm upgrade --install observability-insight-agent charts/observability-insight-agent \<br>      --namespace observability --set image.tag=$CI_COMMIT_SHORT_SHA</pre><p>We can also add support for staging and prod deployments with Git tags controlling production rollout.</p><p><strong>Step 6: Flask API</strong></p><p>The agent exposes:</p><ul><li>/alert → ingest alerts</li><li>/ → health check</li><li>/approve_rollback/&lt;id&gt; → approval callback</li></ul><pre>@app.route(&#39;/alert&#39;, methods=[&#39;POST&#39;])<br>def handle_alert():<br>    ...</pre><h3><strong>Benefits</strong></h3><ul><li><strong>Faster incident triage</strong> with AI-generated root causes.</li><li><strong>Automated rollback</strong> for high-confidence deployment-related issues.</li><li><strong>Centralized Slack notifications</strong> with triage summaries.</li></ul><p>This application could be further enhanced with actionable buttons in Slack, Persist the triage history in a database for auditability. We can also extend AI model for more scenarios</p><h3><strong>Conclusion</strong></h3><p>With this agent, teams can combine <strong>AI triage, observability, and automation</strong> to detect, analyze, and remediate issues faster than ever — reducing downtime and improving system reliability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0373e715c94c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Liferay on Kubernetes with Postgres DB and Elasticsearch]]></title>
            <link>https://yusuf-azaz.medium.com/deploying-liferay-on-kubernetes-with-postgres-db-and-elasticsearch-720cb2daa74b?source=rss-c664523b63a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/720cb2daa74b</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[helm-chart]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[liferay-portal]]></category>
            <category><![CDATA[liferay-dxp]]></category>
            <dc:creator><![CDATA[Yusuf Azaz]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 04:01:29 GMT</pubDate>
            <atom:updated>2025-02-24T04:01:29.215Z</atom:updated>
            <content:encoded><![CDATA[<p>Liferay is a powerful <strong>enterprise-grade Digital Experience Platform (DXP)</strong> designed to help businesses create and manage <strong>web portals, intranets, and customer self-service solutions</strong>. It provides a feature-rich framework for <strong>content management, workflow automation, and collaboration</strong>, making it a preferred choice for organizations looking to enhance digital experiences for employees, partners, and customers.</p><p>Built on <strong>Java</strong> and extensible through <strong>OSGi (Open Services Gateway Initiative) modules</strong>, Liferay offers a flexible and modular architecture. This allows developers to <strong>customize and extend</strong> its functionalities based on business needs, ensuring adaptability to evolving enterprise requirements.</p><p><strong>Why Modify the Default Liferay Setup?</strong></p><p>By default, the <strong>official Liferay </strong>comes bundled with <strong>HSQLDB</strong>, an in-memory database that is only intended for <strong>development and testing</strong>. Additionally, while Liferay includes an <strong>embedded Elasticsearch instance</strong> for search functionalities, it is not suitable for <strong>production environments</strong> due to <strong>scalability and persistence limitations</strong>.</p><p>Liferay, however, supports multiple external databases, including <strong>MySQL, MariaDB, and PostgreSQL</strong>, allowing for better performance, reliability, and scalability. To ensure that Liferay is <strong>ready for production deployment</strong>, it is essential to replace its <strong>default embedded components with robust, external services</strong> that can handle real-world workloads efficiently.</p><p><strong>Key Steps to Achieve a Production-Ready Deployment</strong></p><p>To optimize Liferay for a <strong>stable and scalable</strong> Kubernetes-based deployment, we need to:</p><ol><li><strong>Use an external database instead of HSQLDB</strong> — In this guide, we will configure Liferay to use <strong>PostgreSQL</strong>, a widely adopted <strong>relational database</strong> known for its <strong>robust performance, reliability, and scalability</strong>.</li><li><strong>Integrate an external Elasticsearch instance</strong> — Instead of relying on the <strong>embedded Elasticsearch</strong>, we will set up an <strong>external Elasticsearch cluster</strong>, ensuring <strong>high availability, better search performance, and scalability</strong>.</li><li><strong>Create a custom Liferay container image</strong> — Since the default Liferay image <strong>does not include the Postgres JDBC driver</strong>, we will <strong>modify the container image</strong> to include the necessary driver, allowing seamless database connectivity. The corresponding Dockerfile can be found <a href="https://gist.github.com/yusufazaz/5e2a4eaed727f9ac42bb9585b72d979e">here</a>.</li></ol><p><strong>What This Guide Covers</strong></p><p>In this blog, we will walk through the complete <strong>installation and configuration process</strong> for deploying Liferay on <strong>Kubernetes</strong> using <strong>Helm charts</strong>. We will set up and integrate <strong>Postgre and Elasticsearch</strong>, ensuring that Liferay is optimized for a <strong>production-ready environment</strong> with improved <strong>performance, reliability, and maintainability</strong>.</p><p>By following this guide, you will gain a clear understanding of how to deploy and manage Liferay in a Kubernetes environment while leveraging <strong>best practices for database and search service integration</strong>.</p><ol><li><strong>Setting Up PostgreSQL</strong></li></ol><p>Bitnami provides a well-maintained <strong>PostgreSQL Helm chart</strong>, making it easy to deploy PostgreSQL with production-ready configurations.</p><p>Run the following command to add the <strong>Bitnami Helm repo</strong> and update it:</p><pre>helm repo add bitnami https://charts.bitnami.com/bitnami<br>helm repo update</pre><p>Now, deploy PostgreSQL with a custom database name, username, and password.</p><pre>helm install liferay-pg bitnami/postgresql \<br>-f ./postgres-values.yaml \<br>-n liferay7</pre><p>You can modify these values as needed for security and compliance.</p><p>After installation, check if the PostgreSQL pods are running:</p><pre>kubectl get pods -n liferay7</pre><p>You should see output similar to:</p><pre>NAME                                  READY   STATUS    RESTARTS   AGE<br>liferay-pg-postgresql-0               1/1     Running   0          1m</pre><p><strong>2.</strong> <strong>Setting Up Elasticsearch</strong></p><p>Now that PostgreSQL is up and running, the next step is to setup Elasticsearch</p><p>Elasticsearch has an official <strong>Helm chart</strong> provided by Elastic. First, add the repository and update it:</p><pre>helm repo add elastic https://helm.elastic.co<br>helm repo update</pre><p>Now, install Elasticsearch with some custom settings (to run on a local Kubernetes cluster, you may want to disable ssl)</p><pre>helm install liferay-es elastic/elasticsearch \<br> - set replicas=1 \<br> - set minimumMasterNodes=1 \<br> - set resources.requests.memory=1Gi \<br> - set resources.requests.cpu=500m \<br> - set persistence.enabled=true \<br> - set volumeClaimTemplate.resources.requests.storage=10Gi \<br>-f ./esconfig.yaml \<br>-n liferay7</pre><p>You can modify these values as needed.</p><p>Check if the Elasticsearch pods are running:</p><pre>kubectl get pods -n liferay7</pre><p>Expected output:</p><pre>NAME                                  READY   STATUS    RESTARTS   AGE<br>elasticsearch-master-0                1/1     Running   0          1m</pre><p>To check if Elasticsearch is running correctly, use port forwarding:</p><pre>kubectl port-forward svc/elasticsearch-master 9200:9200 -n liferay7<br>curl http://localhost:9200</pre><p>Expected response:</p><pre>{<br>  &quot;name&quot; : &quot; elasticsearch-master-0&quot;,<br>  &quot;cluster_name&quot; : &quot;elasticsearch&quot;,<br>  &quot;version&quot; : {<br>    &quot;number&quot; : &quot;8.5.1&quot;,<br>    &quot;build_flavor&quot; : &quot;default&quot;,<br>    ...<br>  }<br>}</pre><p><strong>3.</strong> <strong>Setting Up Liferay</strong></p><p>Now that we have Elasticsearch and Postgres DB up and running, we need to <strong>configure Liferay</strong> to use this external Elasticsearch and Postgres DB instance instead of the embedded one.</p><p>Liferay’s default container image <strong>does not include the PostgreSQL JDBC driver</strong>, so we need to create a <strong>custom image</strong> with the driver. You can find the <a href="https://gist.github.com/yusufazaz/5e2a4eaed727f9ac42bb9585b72d979e">Dockerfile here at github</a> or you can get the <a href="https://hub.docker.com/repository/docker/yusufazaz/liferay-portal-postgres/general">prebuilt container </a>at docker hub</p><p><strong>3.1 Clone the Liferay Helm Repository</strong></p><p>Next, we will deploy Liferay using Helm and configure it to connect with the previously installed PostgreSQL and Elasticsearch services. The custom Helm chart is available on GitHub. To proceed, clone the Helm repository to your local machine.</p><pre>git clone https://github.com/yusufazaz/liferay-k8-setup.git</pre><p><strong>3.2 Deploy Liferay with Custom Configuration</strong></p><p>Liferay custom configurations are typically managed in <strong>portal-ext.properties</strong> and relevant files under the <strong>osgi</strong> folder. In our case, we need to specify Postgres and Elasticsearch.</p><p>By default, these custom properties are placed in the /mnt/liferay folder, and during startup, Liferay automatically copies them to the appropriate location. This approach works well in a <strong>standard machine installation</strong>, but in a <strong>containerized environment</strong>, it is more effective to define these configurations as <strong>environment variables</strong>.</p><p>To address this, the <strong>Liferay team introduced a standardized naming convention</strong> for environment variables, allowing configurations to be passed directly. You can find more details on this <a href="https://liferay.dev/blogs/-/blogs/liferay-docker-image-features">naming convention here</a>.</p><p>For convenience, these values have been added as <strong>default configurations in </strong><strong>values.yaml</strong>. Users can modify these values <strong>before installation</strong> or <strong>override them at runtime</strong> using Helm commands.</p><pre>  LIFERAY_JDBC_PERIOD_DEFAULT_PERIOD_URL: jdbc:postgresql://liferay-pg-postgresql.liferay7.svc.cluster.local:5432/postgres<br>  LIFERAY_JDBC_PERIOD_DEFAULT_PERIOD_DRIVER_UPPERCASEC_LASS_UPPERCASEN_AME: org.postgresql.Driver<br>  LIFERAY_JDBC_PERIOD_DEFAULT_PERIOD_USERNAME: liferay<br>  LIFERAY_JDBC_PERIOD_DEFAULT_PERIOD_PASSWORD: liferaypassword<br>  LIFERAY_SEARCH_PERIOD_ENGINE_PERIOD_CONNECTION_PERIOD_MODE: REMOTE<br>  LIFERAY_SEARCH_PERIOD_ENGINE_PERIOD_CONNECTION_PERIODINTRANET_PERIOD_URLS: elasticsearch-service.liferay7.svc.cluster.local:9200<br>  LIFERAY_SEARCH_PERIOD_ENGINE_PERIOD_IMPL: com.liferay.portal.search.elasticsearch7.internal.ElasticsearchEngine<br>  LIFERAY_SEARCH_PERIOD_ENGINE_PERIOD_CONNECTION_PERIOD_HTTP_SSL_ENABLED: false</pre><p><strong>Alternative Configuration</strong>: If you prefer not to use <strong>environment variables</strong>, you can provide these values in <strong>portal-ext.properties</strong> via a Kubernetes <strong>ConfigMap</strong>. To enable this, check the values.yaml file for the appropriate <strong>ConfigMap configuration</strong>.</p><p>To deploy Liferay with these configurations, run the following Helm command</p><pre>helm upgrade --install liferay7 -f ./liferay/values.yaml ./liferay --namespace liferay7</pre><p>Check if the Liferay pod is running:</p><pre>kubectl get pods -n liferay7</pre><p>Expected output:</p><pre>NAME                                  READY   STATUS    RESTARTS   AGE<br>liferay7-79f9bbdc59-mp9b8             1/1     Running   0          1m</pre><p>To access Liferay from your local machine, use <strong>port forwarding</strong>:</p><pre>kubectl port-forward svc/liferay7 80:8080</pre><p>Now, open your browser and go to:</p><p><a href="http://localhost:8080/">http://localhost:8080</a></p><p>Login with the default Liferay admin credentials:</p><ul><li><strong>Username:</strong> test@liferay.com</li><li><strong>Password:</strong> test</li></ul><p>Alternatively, if your Kubernetes cluster has an Ingress Controller installed, you can configure an Ingress to access the Liferay installation. A sample Ingress configuration for the NGINX Ingress Controller is available <a href="https://gist.github.com/yusufazaz/aeac797fe4942239a86a3187e85d4099">here</a> on github</p><p><strong>Conclusion</strong></p><p>We successfully deployed Liferay, the Postgres database and the Elasticsearch engine in Kubernetes, configuring Liferay for seamless scalability within minutes. This was made possible by Kubernetes as the container orchestrator and a set of pre-configured container images that streamlined the setup process. The most difficult part has been getting the environment variables names correct.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=720cb2daa74b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Request-Based Anomalies with Prometheus, Alertmanager, and Grafana]]></title>
            <link>https://yusuf-azaz.medium.com/detecting-request-based-anomalies-with-prometheus-alertmanager-and-grafana-72d2f1c79799?source=rss-c664523b63a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/72d2f1c79799</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[alertmanager]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Yusuf Azaz]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 21:40:38 GMT</pubDate>
            <atom:updated>2024-11-10T21:40:38.264Z</atom:updated>
            <content:encoded><![CDATA[<p>As applications and services scale, the complexity of maintaining high availability and optimal performance increases. Unexpected issues — like a sudden spike in incoming requests, latency in response times, or a rise in error rates — can impact user experience if not quickly addressed. Detecting these request-based anomalies early allows teams to act preemptively, minimizing downtime and ensuring reliable performance.</p><p>In this blog, we’ll explore how Prometheus, Alertmanager, and Grafana, often known as the “PAG stack,” can be used to monitor, detect, and respond to request-based anomalies in real time.</p><h3>Why Monitor Request-Based Anomalies?</h3><p>Request-based metrics, such as request rate, response time, and error rate, provide a direct window into how users experience your application and services. Anomalies in these metrics can point to underlying issues in your infrastructure. Here are some common examples:</p><ul><li><strong>Sudden increase in requests</strong> could indicate an attack or viral activity, potentially overwhelming the application resources.</li><li><strong>Rising response times</strong> could indicate bottlenecks, such as CPU or memory saturation, a backend or database issues.</li><li><strong>Higher error rates</strong> such as HTTP 500s, can suggest system failures or other application issues.</li></ul><p>Detecting these issues early helps prevent small problems from becoming larger, user-facing incidents.</p><h3>Introduction to the PAG Stack: Prometheus, Alertmanager, and Grafana</h3><p><strong>Prometheus, Alertmanager, and Grafana</strong> form a powerful monitoring stack that’s well-suited for managing request-based metrics. Let’s take a quick look at each tool’s role:</p><ul><li><strong>Prometheus</strong>: A time-series database and monitoring system, Prometheus collects metrics from your applications and stores them for querying. It’s well-known for its powerful query language, PromQL, which allows you to analyze data and set up alerting rules.</li><li><strong>Alertmanager</strong>: Alertmanager handles alerting for Prometheus, managing notifications based on alert conditions defined in Prometheus. It groups, routes, and deduplicates alerts, ensuring that relevant teams are notified of issues.</li><li><strong>Grafana</strong>: Grafana is a visualization tool that integrates seamlessly with Prometheus to create insightful, real-time dashboards. It enables teams to visualize metrics, set up alerts, and analyze historical trends.</li></ul><h3>Setting Up Request-Based Monitoring with Prometheus</h3><p>Let’s break down the steps to configure Prometheus to monitor request-based metrics.</p><h4>1. Instrumenting Your Application</h4><p>The first step is to instrument your application to expose metrics that Prometheus can scrape. Many popular libraries, such as <strong>Prometheus client libraries</strong> for Go, Java, Python, and others, make it easy to expose metrics from your code. Some critical metrics to capture include:</p><ul><li><strong>Request Rate</strong>: Counts the number of requests received by the service over time.</li><li><strong>Response Time</strong>: Measures the time taken for the application to respond to requests.</li><li><strong>Error Rate</strong>: Tracks the number of requests that resulted in errors.</li></ul><p>Example of Prometheus client metrics (/metrics) in Java:</p><pre>import io.prometheus.client.Counter;<br><br>public class MetricsExample {<br>    static final Counter requestCounter = Counter.build()<br>            .name(&quot;requests_total&quot;)<br>            .help(&quot;Total requests.&quot;)<br>            .register();<br><br>    public static void handleRequest() {<br>        requestCounter.inc(); // Increment counter by 1 for each request<br>    }<br>}</pre><p>Once your application is instrumented, Prometheus can scrape these metrics, which are then available for querying.</p><h4>2. Defining Alerting Rules in Prometheus</h4><p>Prometheus allows you to define alerting rules using PromQL. Here are some sample alerting rules for common request-based anomalies:</p><p><strong>High Request Rate</strong>:</p><pre>- alert: HighRequestRate<br>  expr: rate(http_requests_total[1m]) &gt; 1000<br>  for: 1m<br>  labels:<br>    severity: warning<br>  annotations:<br>    summary: &quot;High request rate detected&quot;<br>    description: &quot;The request rate has exceeded 1000 requests per minute&quot;</pre><p><strong>High Error Rate</strong>:</p><pre>- alert: HighErrorRate<br>  expr: rate(http_requests_total{status=&quot;500&quot;}[5m]) &gt; 0.05<br>  for: 5m<br>  labels:<br>    severity: critical<br>  annotations:<br>    summary: &quot;High error rate detected&quot;<br>    description: &quot;More than 5% of requests are failing with a 500 status code&quot;</pre><p><strong>Slow Response Time</strong>:</p><pre>- alert: SlowResponseTime<br>  expr: histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) &gt; 1<br>  for: 5m<br>  labels:<br>    severity: warning<br>  annotations:<br>    summary: &quot;Slow response time detected&quot;<br>    description: &quot;95th percentile of response time is above 1 second&quot;</pre><p>These rules ensure that Prometheus detects anomalies and triggers alerts when defined thresholds are crossed.</p><h3>Configuring Alertmanager for Notifications</h3><p>With Alertmanager, you can set up notification channels (e.g., email, Slack, Teams, PagerDuty) to ensure that alerts reaches the right people. Alertmanager can be configured to group alerts by service or severity and send notifications only once per issue, reducing alert fatigue. Here’s an example configuration:</p><pre>route:<br>  group_by: [&#39;alertname&#39;]<br>  receiver: &#39;team-slack&#39;<br><br>receivers:<br>  - name: &#39;team-slack&#39;<br>    slack_configs:<br>      - channel: &#39;#alerts&#39;<br>        send_resolved: true<br>        title: &quot;{{ .CommonAnnotations.summary }}&quot;<br>        text: &quot;{{ .CommonAnnotations.description }}&quot;</pre><p>This setup sends alerts to a Slack channel called #alerts with details on the triggered alert.</p><h3>Visualizing and Analyzing Metrics with Grafana</h3><p>Grafana provides a powerful way to visualize Prometheus metrics, helping you understand trends and spot anomalies at a glance. Here’s how to set up a dashboard to monitor request-based metrics:</p><h4>1. Creating a Dashboard</h4><p>In Grafana, create a new dashboard and add panels for each metric you want to monitor, such as request rate, response time, and error rate. Use PromQL queries to pull data from Prometheus for these panels.</p><p>Example queries:</p><ul><li><strong>Request Rate</strong>: rate(http_requests_total[1m])</li><li><strong>Response Time</strong>: histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))</li><li><strong>Error Rate</strong>: rate(http_requests_total{status=&quot;500&quot;}[5m])</li></ul><h4>2. Setting Up Alerting in Grafana</h4><p>Grafana’s alerting feature allows you to configure visual alerts directly on panels. This provides immediate visual feedback when a metric crosses a predefined threshold.</p><p>For example, set an alert to trigger when the 95th percentile response time exceeds 1 second. This allows you to proactively monitor and respond to performance degradation.</p><h3>Responding to Anomalies: Best Practices</h3><p>Once you’ve set up monitoring, alerting, and visualization, it’s essential to establish a process for responding to anomalies. Here are a few best practices:</p><ol><li><strong>Prioritize Critical Alerts</strong>: Not all alerts need immediate action. Use severity labels to distinguish between warnings and critical issues.</li><li><strong>Set Up Incident Response Playbooks</strong>: Have clear playbooks outlining steps to take for each type of alert. For example, a playbook for high error rates might involve checking logs and scaling services.</li><li><strong>Review Alert Policies Regularly</strong>: Adjust thresholds and add/remove alerts as your application evolves to avoid alert fatigue.</li></ol><h3>Conclusion</h3><p>By combining Prometheus, Alertmanager, and Grafana, you can create a robust system for detecting and responding to request-based anomalies in real time. This monitoring stack enables your team to identify issues before they impact users, improving the reliability and performance of your application. With a well-configured PAG stack, you can stay proactive and keep your services running smoothly.</p><p>We adopted a similar setup in our infrastructure, enabling our SRE team to receive alerts and take proactive measures to ensure service availability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72d2f1c79799" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Scalable Spring Boot Application with Amazon EKS, KEDA, and Redis]]></title>
            <link>https://yusuf-azaz.medium.com/building-a-scalable-spring-boot-application-with-amazon-eks-keda-and-redis-b6ccb614f8ea?source=rss-c664523b63a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6ccb614f8ea</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[keda]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Yusuf Azaz]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 16:20:55 GMT</pubDate>
            <atom:updated>2024-11-07T16:22:31.317Z</atom:updated>
            <content:encoded><![CDATA[<p>As applications grow, handling high volume and efficiently scaling resources become critical to ensure performance. Kubernetes, especially with managed services like Amazon <strong>EKS</strong>, provides a solid foundation for deploying applications at scale. When combined with tools like <strong>KEDA</strong>(Kubernetes Event-driven Autoscaling) for event-driven autoscaling and <strong>Redis</strong> for fast, in-memory data storage, we can achieve dynamic scalability and responsiveness in our applications, at the same time managing the compute cost.</p><h4>Introduction</h4><p>In this post, we’ll walk through deploying a Spring Boot application on Amazon EKS, using Redis for background task queuing and KEDA to enable event-driven scaling. Our Spring Boot application will act as a producer of background tasks (in this case, writing messages to a Redis queue), a Spring Boot worker that will pull tasks from Redis queue and we’ll use KEDA to scale consumers based on the queue length.</p><h4><strong>Prerequisites</strong></h4><p>Before we start, make sure you have the following:</p><ul><li>An AWS account with EKS permissions.</li><li>Basic understanding of Kubernetes, Docker, and Spring Boot.</li><li><em>kubectl</em> and <em>eksctl</em> CLI tools installed.</li><li>JDK17</li></ul><h4><strong>Architecture Overview</strong></h4><p>Our architecture consists of:</p><ol><li><strong>Amazon EKS</strong> to run our containerized Spring Boot application.</li><li><strong>Redis</strong> as the task queue.</li><li><strong>KEDA</strong> for autoscaling based on Redis queue length. You can learn more about <a href="https://keda.sh/docs/2.15/concepts/">KEDA here</a></li><li><strong>Spring Boot</strong> application as both a producer and consumer of tasks.</li></ol><figure><img alt="Kubernetes cluster with KEDA, HPA, Redis and application pods" src="https://cdn-images-1.medium.com/max/701/1*QaWpVQRXDKSgQdZMoQ7zZg.png" /></figure><p>The Spring Boot app will produce background jobs that will be pushed to a Redis list. A separate worker job container, also in Spring Boot, will consume and process tasks from the Redis queue. KEDA will monitor the Redis queue and dynamically scale our worker pods based on the number of jobs.</p><p><strong>Step 1: Set Up EKS Cluster</strong></p><p>If you don’t already have an EKS cluster, create one using eksctl:</p><pre>eksctl create cluster --name demo-cluster --region us-west-2 --nodes 2</pre><p>This command sets up a basic EKS cluster with 2 nodes. You can adjust the configuration as needed.</p><p><strong>Step 1.1: Connect to the Cluster</strong></p><p>Once created, connect to your cluster</p><pre>aws eks - region us-west-2 update-kubeconfig - name demo-cluster</pre><p><strong>Step 2: Deploy Redis on EKS</strong></p><p>To simplify things, let’s use Helm to deploy Redis.</p><p>First, add the Helm repository:</p><pre>helm repo add bitnami https://charts.bitnami.com/bitnami</pre><p>Then, install Redis:</p><pre>helm install redis bitnami/redis</pre><p>Verify that Redis is running:</p><pre>kubectl get pods |grep redis</pre><p><strong>Step 3: Create a Spring Boot Application</strong></p><p>Our Spring Boot application will have two components:</p><ol><li><strong>Producer</strong>: Creates tasks and pushes them to Redis.</li><li><strong>Worker</strong>: Consumes tasks from Redis and processes them.</li></ol><p>For simplicity, I have created just one application, but changing the behavior of the application by making use of Spring profiles.</p><p>Here’s a quick look at our Spring Boot setup:</p><p><strong>3.1 Spring Boot Dependencies</strong></p><p>Go to <a href="https://start.spring.io/">https://start.spring.io/</a> generate the simple maven spring boot project. Or download the entire code from <a href="https://github.com/yusufazaz/keda-redis-app">github</a></p><p>In your pom.xml, include the following dependencies:</p><pre>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>3.2 Redis Configuration</strong></p><p>In application.properties, add Redis configuration:</p><pre>spring.redis.host=redis<br>spring.redis.port=6379</pre><p><strong>3.3 Task Producer</strong></p><p>Our producer will expose an HTTP endpoint that, when accessed, pushes a task to the Redis list.</p><pre>@RestController<br>@RequestMapping(&quot;/tasks&quot;)<br>@Profile(&quot;producer&quot;)<br>public class TaskProducer {<br>  private final RedisTemplate&lt;String, String&gt; redisTemplate;<br><br>  public TaskProducer(RedisTemplate&lt;String, String&gt; redisTemplate) {<br>    this.redisTemplate = redisTemplate;<br>  }<br><br>  @PostMapping(&quot;/create&quot;)<br>  public String createTask(@RequestBody String task) {<br>    Long id = redisTemplate.opsForList().leftPush(&quot;task-queue&quot;, task);<br>    return &quot;Task created! with id &quot;+ id ;<br>  }<br><br>}</pre><p><strong>3.4 Task Worker</strong></p><p>The worker service will pull the task from Redis list and process tasks. Its implemented as CommandLineRunner, once the task is finished, the container will get terminated.</p><pre>@Component<br>@Profile(&quot;worker&quot;)<br>public class TaskWorker implements CommandLineRunner{<br><br>  private final RedisTemplate&lt;String, String&gt; redisTemplate;<br><br>  public TaskWorker(RedisTemplate&lt;String, String&gt; redisTemplate) {<br>    this.redisTemplate = redisTemplate;<br>  }<br><br><br>  @Override<br>  public void run(String... args) throws Exception {<br>    String task = redisTemplate.opsForList().rightPop(&quot;task-queue&quot;);<br>    if(task != null) {<br>      //Process long task<br>      System.out.println(&quot;Processing task: &quot; + task);<br>    }   <br>    <br>  }<br>}</pre><p><strong>Step 4: Dockerize the Application</strong></p><p>To deploy on Kubernetes, we need to containerize the application. Create a Dockerfile.</p><pre>FROM openjdk:17.0.1-jdk-slim<br>COPY target/example-0.0.1-SNAPSHOT.jar app.jar<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;/app.jar&quot;]</pre><p>Then, build and push the Docker image to a registry (e.g., Amazon ECR).</p><pre>docker build -t your-repo /keda-redis-app .<br>docker push your-repo/keda-redis-app</pre><p><strong>Step 5: Deploy the Application to EKS</strong></p><p><strong>5.1 Deploy Producer and Worker Pods</strong></p><p>Define separate Deployment and Service files for both the producer and worker pods. Here’s an example producer.yaml.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: task-producer<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: task-producer<br>  template:<br>    metadata:<br>      labels:<br>        app: task-producer<br>    spec:<br>      containers:<br>      - name: task-producer<br>        image: docker.io/your-repo/keda-redis-app:stable<br>        ports:<br>        - containerPort: 8080<br>        env:<br>        - name: spring.data.redis.host<br>          value: redis<br>        - name: spring.profiles.active<br>          value: default,producer<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: task-producer-svc<br>spec:<br>  selector:<br>    app: task-producer<br>  ports:<br>  - protocol: TCP<br>    port: 80<br>    targetPort: 8080</pre><p>Apply the deployment with:</p><pre>kubectl apply -f producer.yaml</pre><p><strong>5.2 Set Up KEDA for Autoscaling</strong></p><p>Add KEDA to your cluster:</p><pre>helm repo add kedacore https://kedacore.github.io/charts<br>helm install keda kedacore/keda - namespace keda - create-namespace</pre><p>With our current setup, we will create a new job for each task in redis list, once the task is finished container will be deleted. To accomplish this we need a KEDA ScaledJob as worker.</p><p>Here’s an example of ScaledJob deployment:</p><pre>apiVersion: keda.sh/v1alpha1<br>kind: ScaledJob<br>metadata:<br>  name: worker-scaler<br>  namespace: default<br>spec:<br>  jobTargetRef:<br>    template:<br>      spec:<br>        containers:<br>        - name: keda-redis-worker<br>          image: docker.io/yusufazaz/keda-redis-app:stable<br>          imagePullPolicy: Always<br>          env:<br>          - name: spring.data.redis.host<br>            value: redis<br>          - name: spring.profiles.active<br>            value: default,worker<br>          - name: spring.main.web-application-type<br>            value: none            <br>        restartPolicy: Never<br>    backoffLimit: 4  <br>  pollingInterval: 10             # Optional. Default: 30 seconds<br>  maxReplicaCount: 3             # Optional. Default: 100<br>  successfulJobsHistoryLimit: 3   # Optional. Default: 100. How many completed jobs should be kept.<br>  failedJobsHistoryLimit: 3       # Optional. Default: 100. How many failed jobs should be kept.<br>  triggers:<br>  - type: redis<br>    metadata:<br>      address: redis.default.svc.cluster.local:6379<br>      listName: task-queue<br>      listLength: &quot;1&quot;</pre><p>This configuration will scale our worker pods based on the number of tasks in the Redis queue.</p><p>Apply the ScaledJob:</p><pre>kubectl apply -f scaledjob.yaml</pre><p><strong>Step 6: Test the Autoscaling</strong></p><ol><li>Send a request to the producer endpoint to add tasks.</li><li>Monitor the worker pods. As tasks come in Redis, KEDA will create new jobs to create the worker pods to process them.</li></ol><pre>kubectl get jobs<br>kubectl get pods -w</pre><p>You should see worker pods scaling based on the Redis queue size.</p><h4><strong>Conclusion</strong></h4><p>Using EKS, KEDA, and Redis together creates a powerful, dynamic setup for building scalable, event-driven applications. This architecture is ideal for applications that need background processing and elastic scalability. With Redis managing the task queue, KEDA can automatically scale worker pods up or down based on demand — even down to zero when there are no tasks in the queue.</p><p>This setup is also modular and adaptable, allowing for easy component swapping of components. You could extend it further by adding monitoring tools like Prometheus and Grafana or enhancing security with custom IAM roles and policies on AWS.</p><p>The <a href="https://github.com/yusufazaz/keda-redis-app">GitHub</a> repository provides a complete skeleton application, making it easy to get a KEDA-based worker up and running with minimal changes</p><p>KEDA is not limited to EKS, it can be run on other Kubernetes distributions, like K3s or Minikube, or managed Kubernetes services like AKS or GKE.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6ccb614f8ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>