<?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 Dr. Richard Kang on Medium]]></title>
        <description><![CDATA[Stories by Dr. Richard Kang on Medium]]></description>
        <link>https://medium.com/@richard-kang?source=rss-7c96ebaeecf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4QNgz9TSzeZnVzQNtWrESw.png</url>
            <title>Stories by Dr. Richard Kang on Medium</title>
            <link>https://medium.com/@richard-kang?source=rss-7c96ebaeecf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:30:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@richard-kang/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[Conversational AI’s New Voice: Speech-to-Speech Models in Enterprise Generative AI]]></title>
            <link>https://medium.com/doit-international/conversational-ais-new-voice-speech-to-speech-models-in-enterprise-generative-ai-df403bc15292?source=rss-7c96ebaeecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/df403bc15292</guid>
            <category><![CDATA[nova-sonic]]></category>
            <category><![CDATA[voice-ai]]></category>
            <category><![CDATA[enterprise-ai-solutions]]></category>
            <dc:creator><![CDATA[Dr. Richard Kang]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 09:02:57 GMT</pubDate>
            <atom:updated>2025-07-14T09:02:57.930Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A strategic perspective on implementing real-time voice-first AI in the generative era</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGbNyLOIHcqo-j6dqJCWKg.png" /></figure><h3>The Next Frontier: Why Voice, Why Now?</h3><p>Conversational AI has reached an inflection point. Voice is no longer a novelty. It is the most human, efficient, and emotionally intelligent way for enterprises to connect with customers, employees, and partners. Today, speech-to-speech generative AI finally makes these voice-first experiences practical, scalable, and cost-effective. The moment for change is now.</p><h3>Why Now?</h3><p>Why is this happening today? Several key shifts are converging:</p><ul><li>Unified speech-to-speech large language models, like Amazon Nova Sonic, collapse speech recognition, reasoning, and speech generation into a single, real-time architecture</li><li>Latency is dramatically reduced while conversation quality improves</li><li>Customers and employees expect seamless, voice-based interactions more than ever</li></ul><p>The combination of mature generative technology and rising expectations is redefining what’s possible — and what’s competitive.</p><h3>What Is a Voice AI Assistant?</h3><p>A voice AI assistant is a conversational agent that can listen, reason, and respond in natural spoken language, managing complex, multi-turn dialogues in real time. Designed with enterprise-grade security and governance in mind, these assistants are a far cry from traditional scripted bots.</p><p>They are capable of:</p><ul><li>Responding fluidly without robotic pauses</li><li>Mirroring emotion and tone</li><li>Understanding nuanced user intent</li><li>Integrating with enterprise knowledge and performing actions</li></ul><p>That makes them perfect for use cases such as HR interviewing, customer service, proactive sales calls, or employee coaching.</p><h3>The Business Value of Voice Generative AI</h3><p>For senior leaders evaluating voice AI, the business case is compelling:</p><ul><li>Reduce operational costs by automating routine voice interactions</li><li>Improve customer satisfaction through more natural, empathetic conversations</li><li>Serve users around the clock, across languages and geographies</li><li>Enable new revenue streams through proactive, voice-based outreach</li><li>Empower employees with instant, on-demand voice knowledge assistants</li></ul><p>Voice is the channel people prefer. Generative AI finally makes it scalable, secure, and consistent.</p><h3>From STT→LLM→TTS to Unified Speech-to-Speech: A Paradigm Shift</h3><p>Traditionally, voice AI systems have been built using a <em>cascaded pipeline</em> of separate components. This pipeline is often represented as STT→LLM→TTS, which stands for Speech-to-Text→Large Language Model→Text-to-Speech. In a typical voice assistant or call bot, spoken input goes through the following steps:</p><ol><li><strong>Automatic Speech Recognition (ASR)</strong>: The user’s speech is converted to text using a speech-to-text model (e.g., Amazon Transcribe or Google Speech API).</li><li><strong>Language Understanding / LLM Processing</strong>: The transcribed text is passed into a language model or dialogue manager (such as an LLM), which generates a text response based on the user’s query and context.</li><li><strong>Text-to-Speech (TTS) Synthesis</strong>: The AI’s text reply is then converted into spoken audio using a voice synthesis engine (e.g., Amazon Polly or Google’s WaveNet).</li><li><strong>Audio Playback</strong>: The synthesized speech is played back to the user as the answer.</li></ol><p>Each of these steps often involved distinct models or services, and they had to be orchestrated in sequence. The Pipecat open-source framework from Daily (used in AWS reference architectures) exemplifies this pipeline approach: it integrates WebRTC for audio streaming, a voice activity detector (to detect when the user is speaking), Amazon Transcribe for ASR, an LLM (Amazon Nova text model) for NLU/NLG, and Amazon Polly for TTS. <strong>Figure 1</strong> below illustrates such a cascaded voice AI architecture in an enterprise setting, where multiple AWS services work in concert to handle a single user query end-to-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXllWq82sV-_0Fz40DtR_Q.png" /><figcaption><em>Figure 1: A traditional cascaded Conversational AI architecture (from AWS Pipecat reference). Voice input travels through WebRTC transport, VAD (voice activity detection), ASR (speech-to-text), an LLM for NLU/NLG, and TTS for the response. Each component adds processing time and potential points of failure.</em></figcaption></figure><p>While this modular pipeline has the advantage of leveraging specialized components for each task, it also comes with drawbacks. The hand-off between services introduces <strong>latency</strong> — users must often finish speaking before the AI starts formulating a response, leading to noticeable pauses. Each component can also introduce errors (e.g., transcription mistakes or robotic-sounding TTS output), which may compound and reduce the overall conversational quality. Maintaining conversational <strong>coherence</strong> can be challenging when the ASR and TTS are unaware of each other’s nuances or the conversation’s emotional tone. In short, the interactions can feel less natural due to system delays and the mismatch of disjointed parts.</p><h3>Amazon Nova Sonic: A Technology Breakthrough</h3><p>Amazon’s Nova Sonic is a major leap forward. Instead of gluing together separate speech-to-text, reasoning, and text-to-speech components, Nova Sonic unifies the entire conversational process into a single, streamlined, and secure pipeline.</p><p>At a glance, Nova Sonic can:</p><ul><li>Listen and understand in real time</li><li>Generate human-like responses</li><li>Speak with expressive, adaptive voices</li><li>Perform function calls to take action</li><li>Ground answers in enterprise knowledge</li></ul><p>It is delivered as an API through Bedrock, so there is no need to host or train models yourself. This simplicity removes barriers to production adoption, even in regulated or security-sensitive environments.</p><h3>From Vision to Execution: How DoiT Helps</h3><p>At DoiT International, we believe every successful voice AI initiative depends on three essential pillars:</p><p>✅ Natural conversation powered by Nova Sonic’s unified speech-to-speech capabilities<br>✅ Real-time infrastructure built on secure WebRTC, streaming, and containerised microservices<br>✅ Enterprise-grade controls for compliance, governance, and monitoring</p><p>Our team helps organizations put these pillars into practice with a well-architected framework that translates research into secure, scalable, real-world deployments.</p><p><strong>How it comes together</strong>:</p><p>The reference blueprint brings together a secure WebRTC front end, containerized microservices on AWS Fargate, and a Bedrock-managed Nova Sonic backend for real-time, voice-to-voice conversation. Role-based IAM, secure secrets, CloudFront distribution, and comprehensive observability complete the design, ensuring confidence at scale.</p><p>For more information, please visit our <a href="https://github.com/doitintl/amazon-nova-architecture-reference">reference GitHub repository</a>. Please note that this repository is intended for evaluation and testing purposes only and is not yet suitable for production deployment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKn0J7NvomDtlIAMxPm2aA.png" /></figure><p><em>Figure 1: High-level architecture diagram showing the complete system integration between frontend components, backend services, and AWS cloud resources.</em></p><h3>AWS Architecture Components</h3><p>The Nova Sonic implementation utilizes several key AWS services:</p><ol><li><strong>Nova Sonic Service<br></strong>✅ Core speech-to-speech AI capabilities<br>✅ Real-time audio processing<br>✅ Streaming response generation<br>✅ Voice customization options</li><li><strong>Amazon Bedrock<br></strong>✅ Foundation model integration<br>✅ Context-aware response generation<br>✅ Function calling capabilities<br>✅ Knowledge management</li><li><strong>Container Services<br></strong>✅ ECS Fargate for containerised backend services<br>✅ Auto-scaling based on demand<br>✅ Resource optimization<br>✅ Deployment automation</li><li><strong>Supporting Services<br></strong>✅ CloudFront for global content delivery<br>✅ DynamoDB for state management<br>✅ S3 for recording storage<br>✅ CloudWatch for observability</li></ol><h3>Key Integration Points</h3><p>The architecture is built around several critical integration points:</p><ol><li><strong>Frontend-Backend Integration<br></strong>✅ WebRTC signaling via FastAPI endpoints<br>✅ Secure room credential exchange<br>✅ Media stream initialization<br>✅ Connection state synchronization</li><li><strong>Backend-AWS Integration<br></strong>✅ Secure AWS service authentication<br>✅ Streaming connections to Nova Sonic<br>✅ State synchronization with DynamoDB<br>✅ Monitoring integration with CloudWatch</li><li><strong>Pipeline Component Integration<br></strong>✅ Standardized frame interfaces<br>✅ Event-driven communication<br>✅ Bidirectional data flow<br>✅ Modular component architecture</li></ol><h3>Security and Scaling Considerations</h3><p>The implementation incorporates enterprise-grade security and scaling features:</p><ol><li><strong>Security Measures<br></strong>✅ Token-based room authentication<br>✅ Encrypted media transmission<br>✅ Secure credential management<br>✅ Role-based access control</li><li><strong>Scaling Strategy<br></strong>✅ Horizontal scaling of backend services<br>✅ Connection pooling for efficient resource use<br>✅ Regional deployment for global coverage<br>✅ Auto-scaling based on connection metrics</li><li><strong>Resilience Features<br></strong>✅ Automatic reconnection handling<br>✅ Graceful degradation during service disruptions<br>✅ Comprehensive error handling<br>✅ Session recovery mechanisms</li></ol><p>This architecture provides a blueprint for organizations seeking to implement Nova Sonic in enterprise environments, with particular attention to security, scalability, and integration with existing systems.</p><h3>Voice Processing Pipeline Architecture</h3><p>Amazon Nova Sonic’s breakthrough capability is built on an advanced voice processing pipeline that enables near real-time speech-to-speech interactions. Unlike traditional voice assistants that process complete utterances before responding, Nova Sonic continuously processes audio streams bidirectionally, enabling natural conversation flow with minimal latency.</p><p>The voice processing pipeline consists of the following key components:</p><ol><li><strong>Audio Capture and Streaming Layer<br></strong>✅ WebRTC protocol for real-time audio transmission<br>✅ Browser-based audio processing with echo cancellation and noise reduction<br>✅ Adaptive bitrate encoding based on network conditions</li><li><strong>Speech Recognition Component<br></strong>✅ Continuous streaming ASR (Automatic Speech Recognition)<br>✅ Low-latency phoneme-level recognition<br>✅ Context-aware language modeling for improved accuracy</li><li><strong>Semantic Processing Engine<br></strong>✅ Real-time intent detection while user is speaking<br>✅ Multi-turn context management for conversation coherence<br>✅ Query formulation and optimization for LLM interaction</li><li><strong>Nova Sonic Generative AI Backend<br></strong>✅ Streaming token generation with minimal buffering<br>✅ Neural speech synthesis with voice customization<br>✅ Prosody and tone control for natural speech output</li><li><strong>Output Generation and Mixing<br></strong>✅ Dynamic audio mixing for seamless conversation<br>✅ Latency optimization techniques<br>✅ Real-time feedback loop for audio quality control</li></ol><h3>WebRTC Communication Flow</h3><p>The WebRTC implementation enables secure, low-latency bidirectional audio streams between the client application and the Nova Sonic service:</p><ol><li><strong>Session Establishment<br></strong>✅ ICE (Interactive Connectivity Establishment) protocol identifies optimal network paths<br>✅ STUN/TURN servers facilitate NAT traversal<br>✅ SDP (Session Description Protocol) negotiates media capabilities</li><li><strong>Secure Media Transmission<br></strong>✅ DTLS (Datagram Transport Layer Security) provides encryption<br>✅ SRTP (Secure Real-time Transport Protocol) ensures secure audio streaming<br>✅ Bandwidth adaptation based on network conditions</li><li><strong>Audio Processing<br></strong>✅ Client-side audio processing (echo cancellation, noise suppression)<br>✅ Server-side audio enhancement<br>✅ Packet loss concealment techniques</li></ol><h3>AWS Architecture and Function Orchestration</h3><p>The implementation leverages several AWS services in a scalable, resilient architecture:</p><ol><li><strong>Client-Facing Components<br></strong>✅ CloudFront distribution for global content delivery<br>✅ Application Load Balancer for traffic distribution<br>✅ ECS Fargate for containerized application hosting</li><li><strong>Processing Pipeline<br></strong>✅ Amazon Bedrock for generative AI capabilities<br>✅ Amazon Transcribe for speech recognition<br>✅ Amazon Polly for speech synthesis<br>✅ Custom Lambda functions for orchestration</li><li><strong>Backend Services<br></strong>✅ DynamoDB for session management and metadata<br>✅ Parameter Store for secure credential management<br>✅ CloudWatch for comprehensive logging and monitoring</li><li><strong>Security Layer<br></strong>✅ ACM certificates for TLS encryption<br>✅ IAM roles for fine-grained access control<br>✅ AWS WAF for web application firewall protection</li></ol><p>The AWS implementation utilises infrastructure as code (IaC) through AWS CDK, enabling reproducible deployments and consistent environments. The architecture follows AWS Well-Architected Framework principles for security, reliability, performance efficiency, cost optimization, and operational excellence.</p><h3>Performance Optimization</h3><p>Nova Sonic’s low-latency performance is achieved through several technical optimizations:</p><ol><li><strong>Streaming Inference Optimization<br></strong>✅ Parallel processing of audio chunks<br>✅ Adaptive buffering strategies<br>✅ Early response generation based on partial inputs</li><li><strong>Network Latency Reduction<br></strong>✅ Edge computing deployment model<br>✅ Connection pooling for backend services<br>✅ Regional deployment for proximity to end-users</li><li><strong>Resource Scaling<br></strong>✅ Auto-scaling ECS services based on demand<br>✅ Reserved capacity for consistent performance<br>✅ Workload distribution across availability zones</li></ol><h3>Frontend Components Implementation</h3><p>The frontend implementation of Nova Sonic demonstrates how modern web technologies can enable real-time voice interactions with minimal latency. The implementation in the /vite-client directory showcases a production-ready approach to building voice AI interfaces that feel natural and responsive.</p><h3>WebRTC Client Implementation</h3><p>The client-side WebRTC implementation is encapsulated in the ChatbotClient class within app.js, which handles the connection lifecycle and media management:</p><pre>class ChatbotClient {<br>  constructor() {<br>    // Initialize client state<br>    this.rtviClient = null;<br>    this.videoManager = null;<br>    this.setupDOMElements();<br>    this.setupEventListeners();<br>    this.initializeClientAndTransport();<br>  }<br>  // ...<br>}</pre><p>The implementation leverages specialized libraries:</p><ul><li>@pipecat-ai/client-js: Provides the RTVIClient class for real-time voice interactions</li><li>@pipecat-ai/daily-transport: Enables WebRTC communication through <a href="http://daily.co/">Daily.co</a> infrastructure. The first 10,000 participant minutes is free.</li></ul><p>Key features of the WebRTC implementation include:</p><ol><li><strong>Transport Layer Abstraction<br></strong>✅ Encapsulation of WebRTC complexity through a transport interface<br>✅ Automatic handling of ICE candidate negotiation<br>✅ Seamless reconnection strategies for network disruptions</li><li><strong>Media Stream Management<br></strong>✅ Dynamic track subscription and unsubscription<br>✅ Automatic media format negotiation<br>✅ Optimized media quality based on bandwidth conditions</li><li><strong>Connection State Management<br></strong>✅ Robust state transitions (connecting, connected, disconnected)<br>✅ Event-driven architecture for responsive UI updates<br>✅ Comprehensive error handling for connection failures</li></ol><h3>Microphone and Camera Handling Components</h3><p>The project implements sophisticated media device management through the VideoManager class, which provides:</p><ol><li><strong>Device Initialization and Permission Flow<br></strong>✅ User-friendly camera permission requests<br>✅ Detailed error handling for permission denials<br>✅ Visual feedback during device initialization</li><li><strong>Media Track Management<br></strong>✅ Separate handling of local and remote media tracks<br>✅ Quality optimization for video streams<br>✅ Automatic track cleanup on disconnection</li><li><strong>Media Element Integration<br></strong>✅ Dynamic creation and configuration of audio/video elements<br>✅ Responsive layout adaptation<br>✅ Optimized playback settings for low latency</li></ol><p>This example from VideoManager.js demonstrates how camera streams are initialised:</p><pre>async toggleLocalCamera() {<br>  try {<br>    // Request camera access through the browser<br>    const stream = await navigator.mediaDevices.getUserMedia({ <br>      video: { <br>        width: { ideal: 1280 },<br>        height: { ideal: 720 }<br>      } <br>    });<br>    <br>    // Store the stream for later use<br>    this._localStream = stream;<br>    <br>    // Update the local video element with this stream<br>    this.localVideo.srcObject = stream;<br>    <br>    // Ensure the video plays<br>    await this.localVideo.play();<br>  } catch (error) {<br>    // Handle permission errors with user-friendly messaging<br>  }<br>}</pre><h3>User Interface for Voice Interaction</h3><p>The user interface is designed for intuitive voice interaction with the following features:</p><ol><li><strong>Connection Controls<br></strong>✅ Clear visual indicators of connection state<br>✅ One-click connect/disconnect functionality<br>✅ Permissions management interface</li><li><strong>Visual Feedback<br></strong>✅ Real-time transcription display<br>✅ Animated visual indicators during bot speech<br>✅ Connection status indicators</li><li><strong>Debug Capabilities<br></strong>✅ Comprehensive logging interface<br>✅ Network statistics monitoring<br>✅ Audio level visualization</li></ol><h3>Key Frontend Technologies and Libraries</h3><p>The frontend implementation leverages several modern web technologies:</p><ol><li><strong>Vite</strong> — For fast development and optimised production builds</li><li><strong>WebRTC APIs</strong> — For real-time audio/video communication</li><li><strong>Media Streams API</strong> — For accessing device cameras and microphones</li><li><strong>Containerization</strong> — Docker configuration for consistent deployment</li><li><strong>Nginx</strong> — For static file serving and optional proxying</li></ol><h3>Connection Management with Backend</h3><p>The frontend-backend connection is managed through a robust protocol that:</p><ol><li><strong>Establishes secure room-based connections<br></strong>✅ Obtains room credentials from the backend /connect endpoint<br>✅ Secures connections with tokens<br>✅ Handles participant events (joining, leaving)</li><li><strong>Manages media transmission efficiently<br></strong>✅ Implements bandwidth adaptation<br>✅ Handles network transitions<br>✅ Provides quality metrics and diagnostics</li><li><strong>Optimizes for low-latency voice interaction<br></strong>✅ Configures audio elements for minimal processing delay<br>✅ Implements audio buffering optimization<br>✅ Uses hardware acceleration when available</li></ol><p>This architecture enables the critical sub-300ms latency that makes Nova Sonic conversations feel natural and fluid.</p><h3>Backend Components Implementation</h3><p>The server-side implementation in the /server directory showcases how to build a scalable, production-ready backend for Nova Sonic voice AI applications. This implementation demonstrates the integration patterns and architectural decisions required to deploy enterprise-grade voice AI solutions.</p><h3>WebRTC using Daily Transport Implementation</h3><p>The backend leverages <a href="http://daily.co/">Daily.co</a>’s infrastructure for WebRTC session management through a specialized transport implementation:</p><pre># Set up Daily transport with video/audio parameters<br>transport = DailyTransport(<br>    room_url,<br>    token,<br>    &quot;Chatbot&quot;,<br>    DailyParams(<br>        audio_in_enabled=True,<br>        audio_out_enabled=True,<br>        video_in_enabled=True,<br>        video_out_enabled=True,<br>        video_out_width=1024,<br>        video_out_height=576,<br>        vad_analyzer=SileroVADAnalyzer(),<br>        transcription_enabled=True,<br>    ),<br>)</pre><p>Key features of the transport implementation include:</p><ol><li><strong>Room Management<br></strong>✅ Dynamic creation of secure rooms<br>✅ Token-based authentication<br>✅ Automatic cleanup of unused resources</li><li><strong>Media Configuration<br></strong>✅ Independent control of audio/video input and output<br>✅ Resolution and quality settings<br>✅ Voice Activity Detection (VAD) integration</li><li><strong>Event Handling<br></strong>✅ Comprehensive event system for transport state changes<br>✅ Participant lifecycle management<br>✅ Recording control and management</li></ol><h3>Function Call Patterns for Tool Integration</h3><p>The implementation demonstrates advanced function calling patterns that enable tool integration with the LLM:</p><pre># Register functions with the LLM service<br>register_functions(llm)</pre><pre># Set up context with function schemas<br>context = OpenAILLMContext(<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: f&quot;{system_instruction}&quot;},<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: &quot;Hello, I&#39;m here for my interview.&quot;,<br>        },<br>    ],<br>    tools=function_tools_schema,<br>)</pre><p>This architecture enables:</p><ol><li><strong>Tool Registration System<br></strong>✅ Dynamic registration of function schemas<br>✅ Type-safe function interfaces<br>✅ Support for synchronous and asynchronous functions</li><li><strong>Context Management<br></strong>✅ Preservation of conversation context across interactions<br>✅ Efficient context windowing for long conversations<br>✅ Stateful conversation tracking</li><li><strong>Function Execution<br></strong>✅ Secure execution of tool functions<br>✅ Error handling and retry mechanisms<br>✅ Result incorporation into the conversation context</li></ol><h3>Pipeline Architecture and Components</h3><p>The backend implements a sophisticated pipeline architecture using the Pipecat framework:</p><pre>pipeline = Pipeline(<br>    [<br>        transport.input(),<br>        rtvi,<br>        context_aggregator.user(),<br>        llm,<br>        ta,<br>        transport.output(),<br>        context_aggregator.assistant(),<br>    ]<br>)</pre><p>This pipeline approach provides:</p><ol><li><strong>Modular Processing Chain<br></strong>✅ Clear separation of responsibilities<br>✅ Pluggable components for customization<br>✅ Standardized frame processing interfaces</li><li><strong>Bidirectional Data Flow<br></strong>✅ Input processing from user to system<br>✅ Output processing from system to user<br>✅ Event propagation in both directions</li><li><strong>Observability Integration<br></strong>✅ Pipeline-level metrics collection<br>✅ Component-level diagnostics<br>✅ Performance monitoring points</li></ol><h3>Audio Processing and Handling</h3><p>The implementation includes sophisticated audio processing capabilities:</p><ol><li><strong>Voice Activity Detection<br></strong>✅ ML-based voice activity detection using Silero VAD<br>✅ Dynamic threshold adjustment<br>✅ Noise-resilient speech detection</li><li><strong>Transcription Management<br></strong>✅ Real-time speech-to-text conversion<br>✅ Partial results handling for immediate feedback<br>✅ Final transcript synchronization</li><li><strong>Audio Output Optimization<br></strong>✅ Dynamic mixing of audio streams<br>✅ Latency management techniques<br>✅ Playback synchronization</li></ol><h3>Integration with AWS Nova Sonic Services</h3><p>The heart of the implementation is the integration with AWS Nova Sonic services:</p><pre># Initialize AWS Nova Sonic LLM service<br>llm = AWSNovaSonicLLMService(<br>    secret_access_key=NOVA_AWS_SECRET_ACCESS_KEY,<br>    access_key_id=NOVA_AWS_ACCESS_KEY_ID,<br>    region=os.getenv(&quot;NOVA_AWS_REGION&quot;, &quot;us-east-1&quot;),<br>    voice_id=os.getenv(&quot;NOVA_VOICE_ID&quot;, &quot;tiffany&quot;),<br>    send_transcription_frames=True<br>)</pre><p>This integration showcases:</p><ol><li><strong>Secure Authentication<br></strong>✅ AWS credential management<br>✅ Role-based access control<br>✅ Secure environment variable handling</li><li><strong>Voice Customization<br></strong>✅ Voice selection and configuration<br>✅ Prosody and speech characteristics<br>✅ Multilingual support options</li><li><strong>Streaming Optimization<br></strong>✅ Real-time token streaming<br>✅ Progressive response generation<br>✅ Minimal latency configuration</li><li><strong>Advanced Features<br></strong>✅ Transcription frame integration<br>✅ Context-aware responses<br>✅ Interruption handling</li></ol><h3>Executive Action Plan for Voice Generative AI</h3><p>Here is a practical playbook to get started:</p><ol><li>Identify which customer or employee experiences could benefit most from faster, more natural voice interactions</li><li>Build a business case focused on cost, experience, or revenue upside</li><li>Evaluate partners who can deliver the right mix of cloud, AI, and security expertise</li><li>Pilot and measure results with clear success criteria</li><li>Put governance and security controls in place for scale</li><li>Roll out in phases, using infrastructure-as-code and proven observability patterns</li></ol><h3>Looking Ahead</h3><p>Voice is the most natural interface we have. Thanks to generative AI, it can now be as scalable, secure, and intelligent as text-based systems. The future of customer and employee engagement will be built on voice-first, human-like conversations.</p><p>For forward-thinking organizations, the moment to invest is right now.</p><p>At DoiT International, we combine deep cloud, security, and generative AI expertise to help you make voice-first solutions a success, reliably and at scale.</p><p><strong>Let’s build the next generation of conversational AI together. Reach out to </strong><a href="https://www.doit.com/"><strong>DoiT International </strong></a><strong>today!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df403bc15292" width="1" height="1" alt=""><hr><p><a href="https://medium.com/doit-international/conversational-ais-new-voice-speech-to-speech-models-in-enterprise-generative-ai-df403bc15292">Conversational AI’s New Voice: Speech-to-Speech Models in Enterprise Generative AI</a> was originally published in <a href="https://medium.com/doit-international">DoiT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting Your LLM Model on Amazon SageMaker for AI-Assisted Coding]]></title>
            <link>https://medium.com/doit-international/hosting-your-llm-model-on-amazon-sagemaker-for-ai-assisted-coding-0e5d5f6208d8?source=rss-7c96ebaeecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e5d5f6208d8</guid>
            <dc:creator><![CDATA[Dr. Richard Kang]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 06:59:42 GMT</pubDate>
            <atom:updated>2025-03-26T06:59:42.231Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Empowering Enterprise Developer Productivity with Secure, Self-Hosted AI Coding Assistants on Amazon SageMaker</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UXL9v9adkiZfWQwP" /></figure><h3>Introduction and Context</h3><p>AI-assisted coding has significantly transformed software development by automating routine tasks, enhancing accuracy, and allowing developers to focus more on complex problem-solving. Enterprises increasingly prefer hosting their LLM models in private environments, primarily to safeguard sensitive intellectual property and proprietary code, comply with data regulations, and enable customization for specific organizational needs.</p><h3>Overview</h3><p>In this blog, we will host a marketplace LLM in your Amazon SageMaker environment. We will use a model from Amazon SageMaker Jumpstart. Most AI-powered autonomous coding agents, such as Roo Code, Cline, and Continue.dev, support open protocols like OpenAI, making LiteLLM an ideal OpenAI proxy for our SageMaker inference.</p><h3>Why Self-Hosted LLM Models?</h3><p>Companies benefit from self-hosted LLM models for:</p><ul><li><strong>Data Privacy and Security</strong>: Hosting internally ensures sensitive data, source codes, and proprietary algorithms are secure.</li><li><strong>Customization</strong>: Tailoring AI models to specific coding styles, business logic, and regulatory requirements.</li><li><strong>Cost Optimization</strong>: Efficient management and optimization of resources reduce costs compared to third-party AI services.</li></ul><h3>Productivity and Example Use Cases</h3><p>AI-assisted coding boosts productivity and efficiency across software development processes, such as:</p><ul><li>Automating boilerplate code generation</li><li>Assisting in debugging and identifying performance bottlenecks</li><li>Enhancing code review processes</li><li>Accelerating onboarding and training for new developers</li></ul><h3>Important Considerations</h3><ul><li><strong>Security and Compliance</strong>: Proper configuration of IAM roles, encryption, and access controls.</li><li><strong>Cost Management</strong>: Regular monitoring and optimization of infrastructure usage.</li><li><strong>Performance Optimization</strong>: Choose suitable SageMaker instance types based on specific workload demands.</li></ul><h3>Amazon SageMaker’s Role in Self-Hosting</h3><p>Amazon SageMaker simplifies self-hosting by offering:</p><ul><li>Access to a wide range of pre-trained LLMs through SageMaker Jumpstart.</li><li>Scalable, secure, and high-performance infrastructure management.</li><li>Smooth integration within AWS services, reducing operational complexity.</li></ul><h3>Benefits of Using Fargate</h3><p>Using AWS Fargate for deploying the LiteLLM proxy significantly reduces operational overhead by:</p><ul><li>Eliminating the need for manual infrastructure management and server maintenance.</li><li>Automatically handling scaling and availability, ensuring consistent performance.</li><li>Reducing security management complexity through isolation and AWS-managed environments.</li></ul><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*jlQggP7CEl3ME76HKmzXmg.png" /></figure><ol><li>Deploy a model to the Amazon SageMaker endpoint for real-time inference;</li><li>Engineers using AI-powered coding assistants in local IDEs, such as VSCodium, connect securely to the LiteLLM OpenAI proxy via a secured channel to invoke the LiteLLM OpenAI Proxy.</li></ol><h3>Overview of steps</h3><p>First, we will deploy a pre-trained model as the Amazon SageMaker endpoint. Then, we will run an OpenAI proxy with LiteLLM as an ECS service.</p><p>Developers can now connect to the OpenAI proxy. For simplicity, this tutorial will connect via the public IP of the ECS task.</p><h3>Step 1: Deploy a pre-trained model to Amazon SageMaker</h3><p><strong>Prerequisite</strong>: Before we provision an Amazon SageMaker endpoint, you might need to make sure your account has a quota of at least 1 for the instance to be used for the endpoint, which you can check on <a href="https://us-east-1.console.aws.amazon.com/servicequotas/home/services/sagemaker/quotas">https://console.aws.amazon.com/servicequotas/home/services/sagemaker/quotas</a>. We will be using ml.g5.12xlarge , so you will need at least 1 for your account. Otherwise, you can raise a request by selecting <strong>“Request increase at account level.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*YD62BvQXxR5t5E8FR0dxEg.png" /></figure><ol><li>If you don’t have an existing Amazon SageMaker execution role (<a href="https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html</a>), create an IAM role for the SageMaker execution and let’s call it AmazonSageMaker-Endpoints-ExecutionRole, attach the managed policy arn:aws:iam::aws:policy/AmazonSageMakerFullAccessand trust policy for sagemaker.amazonaws.com:</li></ol><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;Service&quot;: &quot;sagemaker.amazonaws.com&quot;<br>            },<br>            &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>        }<br>    ]<br>}</pre><p>2. Identify the VPC, the private Subnets, and the Amazon SageMaker endpoint that will be deployed.</p><p>3. Create an S3 VPC endpoint so that the Amazon SageMaker endpoint can download the pre-trained model from the S3 bucket:</p><pre>aws ec2 create-vpc-endpoint \<br>    --private-dns-enabled \<br>    --vpc-id &lt;vpc-id&gt; \<br>    --service-name com.amazonaws.&lt;region&gt;.s3 \<br>    --route-table-ids &lt;route-table-id&gt;</pre><p>If the command is executed successfully, the route table should have the VPC Endpoint along with the NAT, such as</p><pre>% aws ec2 describe-route-tables --route-table-ids &lt;route-table-id&gt; --query &#39;RouteTables[*].Routes&#39;<br>[<br>    [<br>        {<br>            &quot;DestinationCidrBlock&quot;: &quot;10.0.0.0/23&quot;,<br>            &quot;GatewayId&quot;: &quot;local&quot;,<br>            &quot;Origin&quot;: &quot;CreateRouteTable&quot;,<br>            &quot;State&quot;: &quot;active&quot;<br>        },<br>        {<br>            &quot;DestinationCidrBlock&quot;: &quot;0.0.0.0/0&quot;,<br>            &quot;NatGatewayId&quot;: &quot;nat-&lt;NAT GW ID&gt;&quot;,<br>            &quot;Origin&quot;: &quot;CreateRoute&quot;,<br>            &quot;State&quot;: &quot;active&quot;<br>        },<br>        {<br>            &quot;DestinationPrefixListId&quot;: &quot;pl-63a5400a&quot;,<br>            &quot;GatewayId&quot;: &quot;vpce-&lt;VPCE ID&gt;&quot;,<br>            &quot;Origin&quot;: &quot;CreateRoute&quot;,<br>            &quot;State&quot;: &quot;active&quot;<br>        }<br>    ]<br>]</pre><p>3. Create a Security Group ecs-sagemaker-endpoint with the following :</p><p>Inbound rule:</p><ul><li>Protocol: HTTPS (443)</li><li>Source: The security group itself (self-referential)</li></ul><p>Outbound rule</p><ul><li>Protocol: HTTPS (443)</li><li>Destination: S3 VPC endpoint</li></ul><blockquote>Note: As a cybersecurity good practice, default Security Group should not allow any inbound or outbound rules. Details can be found at <a href="https://docs.aws.amazon.com/securityhub/latest/userguide/ec2-controls.html#ec2-2">https://docs.aws.amazon.com/securityhub/latest/userguide/ec2-controls.html#ec2-2</a></blockquote><ol><li>Identify your model from Amazon SageMaker Jumpstart (e.g., Qwen2, Mistral, Llama 3.2). The list of pre-trained models can be found at <a href="https://sagemaker.readthedocs.io/en/stable/doc_utils/pretrainedmodels.html"><em>https://sagemaker.readthedocs.io/en/stable/doc_utils/pretrainedmodels.html</em></a><em>.</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONdCKPB1qKW6Rw63CdKwAA.png" /></figure><p>2. Note the Model ID and version to create an Amazon SageMaker model:</p><pre>from sagemaker.jumpstart.model import JumpStartModel<br>jump_start_model = JumpStartModel(<br>    model_id=&quot;huggingface-llm-qwen2-7b-instruct&quot;,<br>    model_version=&quot;1.2.0&quot;,<br>    role=&quot;AmazonSageMaker-Endpoints-ExecutionRole&quot;,# or the relevant Amazon SageMaker execution role<br>    vpc_config={<br>        &quot;Subnets&quot;: [ &quot;Private Subnets&quot; ],<br>        &quot;SecurityGroupIds&quot;: [ &quot;ecs-sagemaker-endpoint&quot; ]<br>    },<br>)<br>jump_start_model.deploy(<br>    initial_instance_count=1, <br>    instance_type=&quot;ml.g5.12xlarge&quot;,<br>    accept_eula=True,<br>    endpoint_name=&quot;jumpstart-model&quot;<br>)</pre><p>Confirm your endpoint status using AWS CLI:</p><pre>% aws sagemaker list-endpoints<br>{<br>    &quot;Endpoints&quot;: [<br>        {<br>            &quot;EndpointName&quot;: &quot;jumpstart-model&quot;,<br>            &quot;EndpointArn&quot;: &quot;arn:aws:sagemaker:&lt;AWS REGION&gt;:&lt;AWS ACCOUNT ID&gt;:endpoint/jumpstart-model&quot;,<br>            &quot;CreationTime&quot;: &quot;&lt;CreationTime&gt;&quot;,<br>            &quot;LastModifiedTime&quot;: &quot;&lt;LastModifiedTime&gt;&quot;,<br>            &quot;EndpointStatus&quot;: &quot;InService&quot;<br>        }<br>    ]<br>}</pre><h3>Step 2: Deploy the OpenAI Proxy using Amazon Elastic Container Service (ECS)</h3><blockquote>Details on how to configure LiteLLM prox can be found in <a href="https://docs.litellm.ai/docs/proxy/configs">https://docs.litellm.ai/docs/proxy/configs</a></blockquote><ol><li>Create a configuration YAML file (config.yaml) to map the SageMaker endpoint:</li></ol><pre>model_list:<br>  - model_name: jumpstart-model<br>    litellm_params:<br>      model: sagemaker/jumpstart-model # uses sagemaker namespace, and point to the Amazon SageMaker endpoint name</pre><p>2. Upload config.yaml to an S3 bucket.</p><p>3. Define your ECS container (container-definition.json):</p><pre>[<br>    {<br>        &quot;name&quot;: &quot;litellm&quot;,<br>        &quot;image&quot;: &quot;ghcr.io/berriai/litellm:main-latest&quot;,<br>        &quot;cpu&quot;: 0,<br>        &quot;portMappings&quot;: [<br>            {<br>                &quot;containerPort&quot;: 4000,<br>                &quot;hostPort&quot;: 4000,<br>                &quot;protocol&quot;: &quot;tcp&quot;<br>            }<br>        ],<br>        &quot;essential&quot;: true,<br>        &quot;environment&quot;: [<br>            {<br>                &quot;name&quot;: &quot;LITELLM_CONFIG_BUCKET_OBJECT_KEY&quot;,<br>                &quot;value&quot;: &quot;config.yaml&quot;<br>            },<br>            {<br>                &quot;name&quot;: &quot;LITELLM_CONFIG_BUCKET_NAME&quot;,<br>                &quot;value&quot;: &quot;&lt;S3 bucket&gt;&quot;<br>            },<br>            {<br>                &quot;name&quot;: &quot;LITELLM_MASTER_KEY&quot;,<br>                &quot;value&quot;: &quot;&lt;API key to call the proxy, such as sk-123123&gt;&quot;<br>            }<br>        ],<br>        &quot;mountPoints&quot;: [],<br>        &quot;volumesFrom&quot;: [],<br>        &quot;logConfiguration&quot;: {<br>            &quot;logDriver&quot;: &quot;awslogs&quot;,<br>            &quot;options&quot;: {<br>                &quot;awslogs-group&quot;: &quot;/ecs/litellm&quot;,<br>                &quot;awslogs-create-group&quot;: &quot;true&quot;,<br>                &quot;awslogs-region&quot;: &quot;us-east-1&quot;,<br>                &quot;awslogs-stream-prefix&quot;: &quot;ecs&quot;<br>            }<br>        },<br>        &quot;systemControls&quot;: []<br>    }<br>]</pre><p>3. Create an IAM role for the ECS task role with the least privilege as below:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;Statement1&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;sagemaker:InvokeEndpoint&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:sagemaker:&lt;AWS REGION&gt;:&lt;AWS ACCOUNT ID&gt;:endpoint/jumpstart-model&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>4. Register the ECS task definition:</p><pre>aws ecs register-task-definition \<br>    --family litellm-task \<br>    --requires-compatibilities FARGATE \<br>    --cpu 1024 \<br>    --memory 2048 \<br>    --network-mode awsvpc \<br>    --runtime-platform cpuArchitecture=ARM64 \<br>    --task-role-arn &quot;&lt;ECS Task Role ARN&gt;&quot; \<br>    --container-definitions file://./container-definition.json \<br>    --region $REGION</pre><p>Before creating the ECS service, we need these settings:</p><ul><li>The subnet ID in which the ECS tasks will be running.</li><li>The Security Group allows the ECS tasks to connect to the Amazon SageMaker endpoints. This article was created as ecs-sagemaker-endpoint</li></ul><p>We also need to create a security group for the ECS tasks to download the LiteLLM container image:</p><p>Outbound rule</p><ul><li>Protocol: HTTPS (443)</li><li>Destination: 0.0.0.0/0</li><li>Description: ECS Tasks image download</li></ul><p>Another Security Group for the proxy to the ECS tasks:</p><p>Inbound rule:</p><ul><li>Protocol: LiteLLM port (4000)</li><li>Source: The security group itself (self-referential)</li></ul><p>Outbound rule</p><ul><li>Protocol: LiteLLM port (4000)</li><li>Destination: This security group itself (self-referential)</li><li>Description: Proxy and the ECS tasks</li></ul><p>Create an ECS service with the task definition with the Subnet ID:</p><pre>aws ecs create-service \<br>    --cluster litellm-cluster \<br>    --service-name litellm-service \<br>    --task-definition litellm-task:1 \<br>    --desired-count 1 \<br>    --launch-type FARGATE \<br>    --platform-version LATEST \<br>    --network-configuration &quot;awsvpcConfiguration={subnets=[&lt;SUBNET ID&gt;],assignPublicIp=DISABLED},securityGroups=[&lt;sg-xxx for ecs-sagemaker-endpoint&gt;,&lt;sg-xxx for ecs-443-outbound&gt;,&lt;sg-xxx for proxy-ecs-4000&gt;]&quot; \<br>    --region $REGION</pre><blockquote>Note: As a good cybersecurity practice, ECS services should not have public IP addresses. Details can be found in <a href="https://docs.aws.amazon.com/securityhub/latest/userguide/ecs-controls.html#ecs-5">https://docs.aws.amazon.com/securityhub/latest/userguide/ecs-controls.html#ecs-</a>2</blockquote><p>Retrieve the ECS task private IP:</p><pre>CLUSTER=&quot;litellm-cluster&quot;<br># step 1: get the ECS task id<br>TASK=$(aws ecs list-tasks --cluster ${CLUSTER} --query &quot;taskArns[0]&quot; --output text)<br># step 2: get the eni from from the ECS task<br>ENI=$(aws ecs describe-tasks --cluster $CLUSTER --tasks $TASK --query &quot;tasks[0].attachments[0].details[?name==&#39;networkInterfaceId&#39;].value | [0]&quot; --output text)<br># step 3: get the public ip address of the ENI<br>aws ec2 describe-network-interfaces --network-interface-ids $ENI --query &#39;NetworkInterfaces[0].PrivateIpAddress&#39; --output text </pre><p>Take note of the task private IP, which will be used in the proxy setting.</p><h3>Step 3: Setup a proxy</h3><p>In this example, we will be setting up an EC2 in the same private subnet, to be managed by Amazon System Manager, in order for us to connect to the LiteLLM proxy via SSM port forwarding.</p><ol><li>Create a new Security Group, ssm-outbound-sg, to allow outbound 443 connections:<br>Outbound rule</li></ol><ul><li>Protocol: HTTPS (443)</li><li>Destination: 0.0.0.0/0</li><li>Description: SSM endpoint connections</li></ul><ol><li>Create three VPC endpoints for the EC2 in the private subnet to connect to SSM endpoints</li></ol><pre># Systems Manager endpoint<br>aws ec2 create-vpc-endpoint \<br>    --vpc-id &lt;vpc-id&gt; \<br>    --vpc-endpoint-type Interface \<br>    --service-name com.amazonaws.&lt;region&gt;.ssm \<br>    --subnet-ids &lt;private subnet-id that the EC2 will be provisioned&gt; \<br>    --security-group-ids &lt;security-group-id for EC2 to connect to, such as ec2-ssm&gt;<br><br># SSM Messages endpoint<br>aws ec2 create-vpc-endpoint \<br>    --vpc-id &lt;vpc-id&gt; \<br>    --vpc-endpoint-type Interface \<br>    --service-name com.amazonaws.&lt;region&gt;.ssmmessages \<br>    --subnet-ids &lt;private subnet-id that the EC2 will be provisioned&gt; \<br>    --security-group-ids &lt;security-group-id for EC2 to connect to, such as ec2-ssm&gt;<br><br># EC2 Messages endpoint<br>aws ec2 create-vpc-endpoint \<br>    --vpc-id &lt;vpc-id&gt; \<br>    --vpc-endpoint-type Interface \<br>    --service-name com.amazonaws.&lt;region&gt;.ec2messages \<br>    --subnet-ids &lt;private subnet-id that the EC2 will be provisioned&gt; \<br>    --security-group-ids &lt;security-group-id for EC2 to connect to, such as ec2-ssm&gt;</pre><ol><li>Create a Graviton EC2, such as t4g.small, with Amazon Linux, in the private subnet.</li><li>Attach these security groups to this EC2:</li></ol><ul><li>Litellm-proxy that allows outbound port 4000 to the same security group so that this proxy EC2 can connect to the ECS task</li><li>ssm-outbound-sg to allow EC2 to connect to the SSM endpoints</li></ul><p>3. Once the EC2 is ready, connect using the SSM agent with port forwarding:</p><pre>aws ssm start-session \<br>--target &lt;EC2 instance ID, such as i-012345&gt; \<br>--document-name AWS-StartPortForwardingSessionToRemoteHost \<br>--parameters host=&quot;&lt;ECS Task pivate IP&gt;&quot;,portNumber=&quot;4000&quot;,localPortNumber=&quot;4000&quot;</pre><h3>Step 4: Configure AI-Assisted Coding Environment</h3><p>Install Continue.dev from the marketplace, such as <a href="https://open-vsx.org/extension/Continue/continue">https://open-vsx.org/extension/Continue/continue</a>, and open up the local config.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*jVh0qMrQvCF4BpPvmKe_7Q.png" /></figure><p>Configure the newly created ECS tasks as a model provider:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*xKUqm1vRZ-PKEO3QU-6YXw.png" /></figure><pre>  &quot;models&quot;: [<br>    {<br>      &quot;title&quot;: &quot;litellm&quot;,<br>      &quot;provider&quot;: &quot;openai&quot;,<br>      &quot;model&quot;: &quot;jumpstart-model&quot;,<br>      &quot;apiBase&quot;: &quot;http://localhost:4000/&quot;,<br>    }    <br>  ],</pre><p>Once the configuration is updated, you can attach a file for AI to assist you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*5d9qnKYu6pJU_zr6b-Z5uA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*zWLPbYJY6fBUKUKpXdcz5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hm0eM9vpSPcaj567rZ0Bkw.gif" /></figure><p>NOTE: A secured connection from the engineer&#39;s laptop to the LiteLLM proxy endpoint, such as the use of AWS Client VPN, is strongly recommended.</p><h3>Conclusion and Call to Action</h3><p>Hosting your LLM model on Amazon SageMaker empowers enterprises with unmatched control, robust data privacy, and significant productivity improvements in software development. <a href="https://www.doit.com/">DoiT International</a> can expertly guide your enterprise through the complexities of designing and implementing self-hosted, secure, and cost-effective AI solutions tailored specifically to your needs.</p><p><strong>Ready to enhance your coding capabilities securely? Contact </strong><a href="https://www.doit.com/"><strong>DoiT International </strong></a><strong>today to discuss your Enterprise AI strategy and ensure robust data privacy and compliance.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e5d5f6208d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/doit-international/hosting-your-llm-model-on-amazon-sagemaker-for-ai-assisted-coding-0e5d5f6208d8">Hosting Your LLM Model on Amazon SageMaker for AI-Assisted Coding</a> was originally published in <a href="https://medium.com/doit-international">DoiT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Your Data: Moving Amazon RDS from Public to Isolated Subnet]]></title>
            <link>https://medium.com/doit-international/securing-your-data-moving-amazon-rds-from-public-to-isolated-subnet-54245047a26d?source=rss-7c96ebaeecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/54245047a26d</guid>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Dr. Richard Kang]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 14:41:41 GMT</pubDate>
            <atom:updated>2023-11-01T22:48:50.034Z</atom:updated>
            <content:encoded><![CDATA[<h4>Step-by-Step: Securing your Amazon RDS from the risk of data exfiltration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bAOFyC1rbVrV-WS2Bl5v1A.png" /><figcaption><em>(This image was created with the assistance of Stable Diffusion)</em></figcaption></figure><p>I have been working with customers that host the Amazon RDS database in a VPC subnet with a default route to the internet.</p><p>There could be safety measures in place, such as the “publicly accessible” option of RDS disabled; Security Group inbound rules being restricted to only the allowed EC2 or Lambda; and firewall stateful rules detecting <a href="https://docs.aws.amazon.com/network-firewall/latest/developerguide/aws-managed-rule-groups-threat-signature.html">threats and exploits</a> with SQL signatures. However, incidents such as <a href="https://arxiv.org/pdf/1701.04940.pdf">Target Corporation’s Data breach in 2013</a> show that just blocking incoming internet traffic while allowing all outgoing internet traffic is no longer sufficient to minimize the data exfiltration risk. A threat actor such as command-and-control malware (also known as C&amp;C or C2 malware) can use the outbound traffic over commonly used ports like HTTP:80 and HTTPS:443 for beaconing.</p><p>This article describes the steps to move an Amazon RDS from a public subnet with an internet-bounded route table to an <strong>isolated subnet</strong>, without the need to create a new DB instance using snapshot-restore.</p><p>Any VPC can have 3 types of subnet: a <em>public subnet</em> which has an internet gateway attached to it to allow both incoming and outgoing internet traffic; a <em>private subnet</em> that has a Network Address Translation (NAT) or Internet Egress-only gateway to allow outgoing internet traffic; an <em>isolated subnet</em> allows only traffic within the VPC and has no routes to destinations outside the VPC.</p><p>Hosting the database in an <strong>isolated subnet</strong> can help reduce the risk of data exfiltration, by reducing the attack surface, making it less likely for an attacker such as a C&amp;C malware to find a way to exfiltrate the data.</p><p>However, do note that network isolation is only one of the important security measures to help reduce the risk, but not foolproof to prevent data exfiltration. A chain is only as strong as its weakest link. Every measure in reducing the risk counts.</p><h3>Setting up the test environment with Multi-AZ Amazon RDS</h3><p>To follow the steps of moving the RDS Instance from a public subnet to an isolated subnet, you will need to set up a test environment, consisting of an Amazon RDS in the public subnets of a VPC. The VPC consists of public and isolated subnets.</p><p>Feel free to skip the VPC creation step if you already have Amazon RDS instances in public subnets, and the VPC has isolated subnets.</p><p>We will be creating the AWS resources using CDK. If you are new to CDK, you can follow <a href="https://docs.aws.amazon.com/cdk/v2/guide/hello_world.html">https://docs.aws.amazon.com/cdk/v2/guide/hello_world.htm </a>on how to start.</p><h4>CDK stack that creates a VPC</h4><p>The first step of setting up the test environment is to create a VPC with one public and isolated subnet in each Availability Zone, across two Availability Zones using the CDK stack as below.</p><p>We will export the necessary VPC parameters such as the VPC ID so that we can import them into the stack that creates the RDS in the next step.</p><pre>#!/usr/bin/env node<br>import &#39;source-map-support/register&#39;;<br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br><br>const app = new cdk.App();<br>const vpcStack = new cdk.Stack(app, &quot;vpc-stack&quot;);<br>const vpc = new cdk.aws_ec2.Vpc(vpcStack, `test-vpc`, {<br>    ipAddresses: cdk.aws_ec2.IpAddresses.cidr(&quot;10.0.0.0/20&quot;),<br>    vpcName: `test-vpc`,<br>    enableDnsHostnames: true,<br>    enableDnsSupport: true,<br>    maxAzs: 2,<br>    subnetConfiguration: [<br>        {<br>            name: &quot;public&quot;,<br>            subnetType: cdk.aws_ec2.SubnetType.PUBLIC,<br>            cidrMask: 27<br>        },<br>        {<br>            name: &quot;isolated&quot;,<br>            subnetType: cdk.aws_ec2.SubnetType.PRIVATE_ISOLATED,<br>            cidrMask: 27<br>        },<br>    ]<br>});<br><br>new cdk.CfnOutput(<br>  vpcStack, &#39;testVpcVpcID&#39;, {<br>  value: vpc.vpcId,<br>  description: &#39;Test Vpc ID&#39;,<br>  exportName: &#39;test-vpc-VpcID&#39;,<br>});<br><br>new cdk.CfnOutput(<br>  vpcStack, &#39;testVpcAz&#39;, {<br>  value: vpc.availabilityZones.join(&quot;,&quot;),<br>  description: &#39;Vpc AZs&#39;,<br>  exportName: &#39;test-Vpc-AZs&#39;,<br>});<br><br>new cdk.CfnOutput(<br>  vpcStack, &#39;testVpcPublicSubnets&#39;, {<br>  value: vpc.selectSubnets({<br>    subnetType: cdk.aws_ec2.SubnetType.PUBLIC<br>  }).subnetIds.join(&quot;,&quot;),<br>  description: &#39;Vpc Public Subnet IDs&#39;,<br>  exportName: &#39;test-Vpc-PublicSubnetIds&#39;,<br>});<br><br>new cdk.CfnOutput(<br>  vpcStack, &#39;testVpcIsolatedSubnets&#39;, {<br>  value: vpc.selectSubnets({<br>    subnetType: cdk.aws_ec2.SubnetType.PRIVATE_ISOLATED<br>  }).subnetIds.join(&quot;,&quot;),<br>  description: &#39;Vpc Isolated Subnet IDs&#39;,<br>  exportName: &#39;test-Vpc-IsolatedSubnetIds&#39;,<br>});</pre><p>If cdk deploy vpc-stackis successful, you should see the outputs such as below:</p><pre>✅  vpc-stack<br><br>✨  Deployment time: 76.83s<br><br>Outputs:<br>vpc-stack.testVpcAz = us-east-1a,us-east-1b<br>vpc-stack.testVpcIsolatedSubnets = subnet-03e58f5428463ad26,subnet-06721c9fdaac5f333<br>vpc-stack.testVpcVpcID = vpc-090949477d23289ce<br>vpc-stack.testeVpcPublicSubnets = subnet-0271290b1164913ad,subnet-079b9aaba653c430b</pre><p>Take note of the VPC ID, the Public Subnet IDs, and the Isolated Subnet IDs.</p><p>In this example, these are the parameters that we will be using when creating the Amazon RDS:</p><ul><li>VPC ID: vpc-090949477d23289ce</li><li>Public subnet IDs: subnet-0271290b1164913ad, subnet-079b9aaba653c430b</li><li>Isolated subnet IDs: subnet-06721c9fdaac5f333, subnet-03e58f5428463ad26</li></ul><h4>CDK stack that creates Amazon RDS</h4><p>Next, we will provision an Amazon Postgres RDS in the public subnet of the VPC:</p><blockquote><em>Quick tips on CDK: </em><em>cdk.Fn.importValue() is a </em><a href="https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md#attributes"><em>late-bound attribute</em></a><em>. Therefore, we need to use the CloudFormation string split function </em><em>cdk.Fn.Split() instead of Typescript of string split such as </em>cdk.Fn.importValue(‘test-Vpc-AZs’).split(“,”) <em>which would cause errors such as</em> Some input subnets in :[subnet-0271290b1164913ad,subnet-079b9aaba653c430b] are invalid.</blockquote><pre>#!/usr/bin/env node<br>import &#39;source-map-support/register&#39;;<br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br><br>const app = new cdk.App();<br>const rdsStack = new cdk.Stack(app, &quot;rds-stack&quot;);<br>const vpcLookup = cdk.aws_ec2.Vpc.fromVpcAttributes(<br>  rdsStack, `${rdsStack.stackName}-vpc-lookup`, <br>  &lt;cdk.aws_ec2.VpcAttributes&gt;{<br>    vpcId: cdk.Fn.importValue(&#39;test-vpc-VpcID&#39;),<br>    availabilityZones: cdk.Fn.split(&quot;,&quot;,cdk.Fn.importValue(&#39;test-Vpc-AZs&#39;)),<br>    publicSubnetIds: cdk.Fn.split(&quot;,&quot;,cdk.Fn.importValue(&#39;test-Vpc-PublicSubnetIds&#39;)),<br>    isolatedSubnetIds: cdk.Fn.split(&quot;,&quot;,cdk.Fn.importValue(&#39;test-Vpc-IsolatedSubnetIds&#39;))<br>  });<br>const subnetType: cdk.aws_ec2.SubnetSelection = { subnetType: cdk.aws_ec2.SubnetType.PUBLIC };<br>const subnetGroup = new cdk.aws_rds.SubnetGroup(<br>  rdsStack, `${rdsStack.stackName}-rds-subnetgroup`, <br>  &lt;cdk.aws_rds.SubnetGroupProps&gt;{<br>    subnetGroupName: `${rdsStack.stackName}-rds-subnetgroup`,<br>    vpc: vpcLookup,<br>    vpcSubnets: {<br>      subnets: vpcLookup.selectSubnets(subnetType).subnets<br>    },<br>    description: &quot;RDS subnetgroup&quot;<br>  });<br>const rdsInstance = new cdk.aws_rds.DatabaseInstance(<br>  rdsStack, `${rdsStack.stackName}-rdsInstance`, <br>  &lt;cdk.aws_rds.DatabaseInstanceProps&gt;{<br>    engine: cdk.aws_rds.DatabaseInstanceEngine.postgres({<br>      version: cdk.aws_rds.PostgresEngineVersion.VER_15_3<br>    }),<br>    vpcLookup,<br>    subnetGroup: subnetGroup,<br>    publiclyAccessible: false,<br>    multiAz: true,<br>    credentials: cdk.aws_rds.Credentials.fromSecret(<br>      new cdk.aws_rds.DatabaseSecret( rdsStack, `${rdsStack.stackName}-database-secret`,<br>        &lt;cdk.aws_rds.DatabaseSecretProps&gt;{<br>          username: &quot;dbMaster&quot;,      <br>          secretName: `dbMaster-credential`,      <br>        }<br>      )<br>    ),<br>    instanceIdentifier: `${rdsStack.stackName}-rds`,<br>    instanceType: cdk.aws_ec2.InstanceType.of(cdk.aws_ec2.InstanceClass.BURSTABLE4_GRAVITON, cdk.aws_ec2.InstanceSize.MICRO),<br>    storageType: cdk.aws_rds.StorageType.GP3,      <br>});<br><br>new cdk.CfnOutput(<br>  rdsStack, `${rdsStack.stackName}-rds-name`, {<br>    value: rdsInstance.instanceIdentifier,<br>    description: &#39;RDS instance identifier&#39;<br>}); <br><br>new cdk.CfnOutput(<br>  rdsStack, `${rdsStack.stackName}-subnetgroup-name`, {<br>    value: subnetGroup.subnetGroupName,<br>    description: &quot;RDS Subnet Group Name&quot;<br>});</pre><p>If you have an existing VPC that you would want the RDS to be created in, change the vpcLookup with the relevant values, such as:</p><pre>const vpcLookup = cdk.aws_ec2.Vpc.fromVpcAttributes(rdsStack, `${rdsStack.stackName}-vpc-lookup`, {<br>  vpcId: &quot;vpc-090949477d23289ce&quot;,<br>  availabilityZones: [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;],<br>  publicSubnetIds: [&quot;subnet-0271290b1164913ad&quot;, &quot;subnet-079b9aaba653c430b&quot;],<br>  isolatedSubnetIds: [&quot;subnet-03e58f5428463ad26&quot;, &quot;subnet-06721c9fdaac5f333&quot;],<br>});</pre><p>If cdk deploy rds-stackis successful, you should see the outputs such as below:</p><pre> ✅  rds-stack<br><br>✨  Deployment time: 20.95s<br><br>Outputs:<br>rds-stack.rdsstackrdsname = rds-stack-rds</pre><h4>What have we created?</h4><p>We have created a VPC with two Availability Zones. Each zone has a public and an isolated subnet.</p><p>We also provisioned multi-AZ Amazon RDS in the public subnet of both availability zones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*ArrYkhdECPSMt71ZGpkWHA.png" /><figcaption>Multi-AZ RDS in public subnets</figcaption></figure><h3>Move Amazon RDS from public subnet to isolated subnets</h3><p>We have an RDS Subnet Group that consists of multiple subnets, each for one Availability Zone, for example, the primary instance in AZ-1 and the stand-by instance in AZ-2.</p><p>However, to change the subnet of each instance, we need to remove the instance that is using that subnet, otherwise, if we are to modify the subnet with an RDS instance in that subnet, an error will occur:</p><pre>An error occurred (InvalidParameterValue) when calling the ModifyDBSubnetGroup operation: Some of the subnets to be deleted are currently in use: subnet-0271290b1164913ad</pre><p>Overview of the steps to move the Amazon RDS from the public subnet to the isolated subnet:</p><ol><li>Stop the standby instance to free up the public subnet, so that the RDS subnet group can change that public subnet to the isolated subnet before re-deploying the standby instance in the isolated subnet.</li><li>Promote the standby as primary, and repeat the same on the newly demoted standby instance.</li><li>Updates the state of CDK.</li></ol><h4>Step 1: Move the standby instance</h4><p>Before we start, we need to capture some key parameters:</p><p><strong>Take note of the subnet of Primary and Standby RDS instance</strong></p><p>Run this AWS CLI command to query for the Primary and Secondary Availability Zone:</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone}&quot; --output table<br>------------------------------<br>|     DescribeDBInstances    |<br>+-------------+--------------+<br>|   Primary   |   Standby    |<br>+-------------+--------------+<br>|  us-east-1a |  us-east-1b  |<br>+-------------+--------------+</pre><p>Map the Availability Zone to the Subnets in the RDS Subnet Group with the CLI command:</p><pre>% aws rds describe-db-subnet-groups --db-subnet-group rds-stack-rds-subnetgroup --query &quot;DBSubnetGroups[*].Subnets[*].{AvailabilityZone:SubnetAvailabilityZone.Name,SubnetIdentifier:SubnetIdentifier}&quot; --output table<br>--------------------------------------------------<br>|             DescribeDBSubnetGroups             |<br>+-------------------+----------------------------+<br>| AvailabilityZone  |     SubnetIdentifier       |<br>+-------------------+----------------------------+<br>|  us-east-1b       |  subnet-079b9aaba653c430b  |<br>|  us-east-1a       |  subnet-0271290b1164913ad  |<br>+-------------------+----------------------------+</pre><p>Based on these 2 outputs, we can conclude that</p><ul><li>The primary RDS instance is insubnet-0271290b1164913ad.</li><li>The standby RDS instance is in subnet-079b9aaba653c430b.</li></ul><p><strong>Stop the standby instance and change the subnet</strong></p><p>Modify the RDS instance with modify-db-instance CLI command as below:</p><pre>% aws rds modify-db-instance --db-instance-identifier rds-stack-rds --no-multi-az --apply-immediately --query &quot;DBInstance.MultiAZ&quot;<br>true</pre><p>To confirm if the RDS Instance is a single AZ, rerun the describe-db-instances CLI</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone}&quot; --output table<br>---------------------------<br>|   DescribeDBInstances   |<br>+-------------+-----------+<br>|   Primary   |  Standby  |<br>+-------------+-----------+<br>|  us-east-1a |  None     |<br>+-------------+-----------+</pre><p>Update the RDS Subnet group to replace the public subnet of terminated standby with an isolated subnet of the same availability zone.</p><pre>% aws rds modify-db-subnet-group --db-subnet-group-name rds-stack-rds-subnetgroup --subnet-ids &quot;subnet-0271290b1164913ad&quot; &quot;subnet-06721c9fdaac5f333&quot;<br>{<br>    &quot;DBSubnetGroup&quot;: {<br>        &quot;DBSubnetGroupName&quot;: &quot;rds-stack-rds-subnetgroup&quot;,<br>        &quot;DBSubnetGroupDescription&quot;: &quot;RDS subnetgroup&quot;,<br>        &quot;VpcId&quot;: &quot;vpc-090949477d23289ce&quot;,<br>        &quot;SubnetGroupStatus&quot;: &quot;Complete&quot;,<br>        &quot;Subnets&quot;: [<br>            {<br>                &quot;SubnetIdentifier&quot;: &quot;subnet-0271290b1164913ad&quot;,<br>                &quot;SubnetAvailabilityZone&quot;: {<br>                    &quot;Name&quot;: &quot;us-east-1a&quot;<br>                },<br>                &quot;SubnetOutpost&quot;: {},<br>                &quot;SubnetStatus&quot;: &quot;Active&quot;<br>            },<br>            {<br>                &quot;SubnetIdentifier&quot;: &quot;subnet-06721c9fdaac5f333&quot;,<br>                &quot;SubnetAvailabilityZone&quot;: {<br>                    &quot;Name&quot;: &quot;us-east-1b&quot;<br>                },<br>                &quot;SubnetOutpost&quot;: {},<br>                &quot;SubnetStatus&quot;: &quot;Active&quot;<br>            }<br>        ],<br>        &quot;DBSubnetGroupArn&quot;: &quot;arn:aws:rds:us-east-1:825202810339:subgrp:rds-stack-rds-subnetgroup&quot;,<br>        &quot;SupportedNetworkTypes&quot;: [<br>            &quot;IPV4&quot;<br>        ]<br>    }<br>}</pre><p>Confirm the RDS Subnet Group with describe-db-subnet-groups command:</p><pre>% aws rds describe-db-subnet-groups --db-subnet-group rds-stack-rds-subnetgroup --query &quot;DBSubnetGroups[*].Subnets[*].{AvailabilityZone:SubnetAvailabilityZone.Name,SubnetIdentifier:SubnetIdentifier}&quot; --output table<br>--------------------------------------------------<br>|             DescribeDBSubnetGroups             |<br>+-------------------+----------------------------+<br>| AvailabilityZone  |     SubnetIdentifier       |<br>+-------------------+----------------------------+<br>|  us-east-1a       |  subnet-0271290b1164913ad  |<br>|  us-east-1b       |  subnet-06721c9fdaac5f333  |<br>+-------------------+----------------------------+</pre><p>Re-enable the Multi-AZ deployment with the command modify-db-instance</p><pre>% aws rds modify-db-instance --db-instance-identifier rds-stack-rds --multi-az --apply-immediately --query &quot;DBInstance.MultiAZ&quot; <br>false</pre><p>The modification might take a while, which can be monitored through DBInstanceStatus</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Status:DBInstanceStatus,Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone}&quot; --output table<br>----------------------------------------<br>|          DescribeDBInstances         |<br>+------------+-----------+-------------+<br>|   Primary  |  Standby  |   Status    |<br>+------------+-----------+-------------+<br>|  us-east-1a|  None     |  modifying  |<br>+------------+-----------+-------------+</pre><p>Confirm the standby instances created with describe-db-instances</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Status:DBInstanceStatus,Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone}&quot; --output table<br>-------------------------------------------<br>|           DescribeDBInstances           |<br>+------------+--------------+-------------+<br>|   Primary  |   Standby    |   Status    |<br>+------------+--------------+-------------+<br>|  us-east-1a|  us-east-1b  |  available  |<br>+------------+--------------+-------------+</pre><h4>What do we have now?</h4><p>We have moved the standby instance in the Secondary Availability Zone from the public subnet to the isolated subnet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*_LklVPzQtBqrJVdbmxP2qA.png" /><figcaption>Multi-AZ RDS with the primary in the public subnet and standby in the isolated subnet</figcaption></figure><h4>Step 2: Promote the standby and move the old primary</h4><p>Take note of the RDS endpoint to make sure the endpoint address does not change after failover to ensure availability:</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Status:DBInstanceStatus,Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone,Endpoint:Endpoint.Address}&quot; --output table<br>-----------------------------------------------------------------------------------------------------<br>|                                        DescribeDBInstances                                        |<br>+---------------------------------------------------------+-------------+-------------+-------------+<br>|                        Endpoint                         |   Primary   |   Standby   |   Status    |<br>+---------------------------------------------------------+-------------+-------------+-------------+<br>|  rds-stack-rds.cmkhfj0htgnu.us-east-1.rds.amazonaws.com |  us-east-1a |  us-east-1b |  available  |<br>+---------------------------------------------------------+-------------+-------------+-------------+</pre><blockquote>Note: Make sure you reboot your instance during maintenance windows or low peak hours due to the unavailability of the instances during the reboot.</blockquote><p>Reboot the RDS instance with the parameter --force-failover :</p><pre>aws rds reboot-db-instance --db-instance-identifier rds-stack-rds --force-failover</pre><p>Confirm the failover with describe-db-instances</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Status:DBInstanceStatus,Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone,Endpoint:Endpoint.Address,MultiAZ:MultiAZ}&quot; --output table<br>----------------------------------------------------------------------------------------------------------------<br>|                                              DescribeDBInstances                                             |<br>+---------------------------------------------------------+----------+-------------+-------------+-------------+<br>|                        Endpoint                         | MultiAZ  |   Primary   |   Standby   |   Status    |<br>+---------------------------------------------------------+----------+-------------+-------------+-------------+<br>|  rds-stack-rds.cmkhfj0htgnu.us-east-1.rds.amazonaws.com |  True    |  us-east-1b |  us-east-1a |  available  |<br>+---------------------------------------------------------+----------+-------------+-------------+-------------+</pre><p><strong>Remove the new standby (old primary) that is in the public subnet</strong></p><p>With the new primary in the isolated subnet, proceed to remove the newly demoted standby instance</p><pre>% aws rds modify-db-instance --db-instance-identifier rds-stack-rds --no-multi-az --apply-immediately --query &quot;DBInstance.MultiAZ&quot;<br>true</pre><p>The RDS instance will now be in the modifying status:</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Status:DBInstanceStatus,Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone,Endpoint:Endpoint.Address,MultiAZ:MultiAZ}&quot; --output table<br>----------------------------------------------------------------------------------------------------------------<br>|                                              DescribeDBInstances                                             |<br>+---------------------------------------------------------+----------+-------------+-------------+-------------+<br>|                        Endpoint                         | MultiAZ  |   Primary   |   Standby   |   Status    |<br>+---------------------------------------------------------+----------+-------------+-------------+-------------+<br>|  rds-stack-rds.cmkhfj0htgnu.us-east-1.rds.amazonaws.com |  True    |  us-east-1b |  us-east-1a |  modifying  |<br>+---------------------------------------------------------+----------+-------------+-------------+-------------+</pre><p>Once the RDS instance is in available status, the standby subnet should be freed up for the next step:</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Status:DBInstanceStatus,Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone,Endpoint:Endpoint.Address,MultiAZ:MultiAZ,Pending:PendingModifiedValues}&quot; --output table<br>-------------------------------------------------------------------------------------------------------------<br>|                                            DescribeDBInstances                                            |<br>+---------------------------------------------------------+----------+-------------+----------+-------------+<br>|                        Endpoint                         | MultiAZ  |   Primary   | Standby  |   Status    |<br>+---------------------------------------------------------+----------+-------------+----------+-------------+<br>|  rds-stack-rds.cmkhfj0htgnu.us-east-1.rds.amazonaws.com |  False   |  us-east-1b |  None    |  available  |<br>+---------------------------------------------------------+----------+-------------+----------+-------------+</pre><p>Proceed to modify the RDS subnet group to change the public subnet to the isolated subnet:</p><pre>% aws rds modify-db-subnet-group --db-subnet-group-name rds-stack-rds-subnetgroup --subnet-ids &quot;subnet-03e58f5428463ad26&quot; &quot;subnet-06721c9fdaac5f333&quot;<br>{<br>    &quot;DBSubnetGroup&quot;: {<br>        &quot;DBSubnetGroupName&quot;: &quot;rds-stack-rds-subnetgroup&quot;,<br>        &quot;DBSubnetGroupDescription&quot;: &quot;RDS subnetgroup&quot;,<br>        &quot;VpcId&quot;: &quot;vpc-090949477d23289ce&quot;,<br>        &quot;SubnetGroupStatus&quot;: &quot;Complete&quot;,<br>        &quot;Subnets&quot;: [<br>            {<br>                &quot;SubnetIdentifier&quot;: &quot;subnet-06721c9fdaac5f333&quot;,<br>                &quot;SubnetAvailabilityZone&quot;: {<br>                    &quot;Name&quot;: &quot;us-east-1b&quot;<br>                },<br>                &quot;SubnetOutpost&quot;: {},<br>                &quot;SubnetStatus&quot;: &quot;Active&quot;<br>            },<br>            {<br>                &quot;SubnetIdentifier&quot;: &quot;subnet-03e58f5428463ad26&quot;,<br>                &quot;SubnetAvailabilityZone&quot;: {<br>                    &quot;Name&quot;: &quot;us-east-1a&quot;<br>                },<br>                &quot;SubnetOutpost&quot;: {},<br>                &quot;SubnetStatus&quot;: &quot;Active&quot;<br>            }<br>        ],<br>        &quot;DBSubnetGroupArn&quot;: &quot;arn:aws:rds:us-east-1:825202810339:subgrp:rds-stack-rds-subnetgroup&quot;,<br>        &quot;SupportedNetworkTypes&quot;: [<br>            &quot;IPV4&quot;<br>        ]<br>    }<br>}</pre><p>Redeploy the multi-AZ RDS:</p><pre>% aws rds modify-db-instance --db-instance-identifier rds-stack-rds --multi-az --apply-immediately</pre><p>The RDS instance will be in modifying status with the MultiAZ values pending modification:</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Status:DBInstanceStatus,Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone,Endpoint:Endpoint.Address,MultiAZ:MultiAZ,NewValue:PendingModifiedValues}&quot; --output table<br>-------------------------------------------------------------------------------------------------------------<br>|                                            DescribeDBInstances                                            |<br>+---------------------------------------------------------+----------+-------------+----------+-------------+<br>|                        Endpoint                         | MultiAZ  |   Primary   | Standby  |   Status    |<br>+---------------------------------------------------------+----------+-------------+----------+-------------+<br>|  rds-stack-rds.cmkhfj0htgnu.us-east-1.rds.amazonaws.com |  False   |  us-east-1b |  None    |  modifying  |<br>+---------------------------------------------------------+----------+-------------+----------+-------------+<br>||                                                NewValue                                                 ||<br>|+------------------------------------------------------------+--------------------------------------------+|<br>||  MultiAZ                                                   |  True                                      ||<br>|+------------------------------------------------------------+--------------------------------------------+|</pre><p>Once the RDS Instance is available , the new standby will be deployed in the isolated subnet:</p><pre>% aws rds describe-db-instances --db-instance-identifier rds-stack-rds --query &quot;DBInstances[*].{Status:DBInstanceStatus,Primary:AvailabilityZone,Standby:SecondaryAvailabilityZone,Endpoint:Endpoint.Address,MultiAZ:MultiAZ,NewValue:PendingModifiedValues}&quot; --output table<br>----------------------------------------------------------------------------------------------------------------<br>|                                              DescribeDBInstances                                             |<br>+---------------------------------------------------------+----------+-------------+-------------+-------------+<br>|                        Endpoint                         | MultiAZ  |   Primary   |   Standby   |   Status    |<br>+---------------------------------------------------------+----------+-------------+-------------+-------------+<br>|  rds-stack-rds.cmkhfj0htgnu.us-east-1.rds.amazonaws.com |  True    |  us-east-1b |  us-east-1a |  available  |<br>+---------------------------------------------------------+----------+-------------+-------------+-------------+</pre><h4>What do we have now?</h4><p>We have moved the standby instance in the Secondary Availability Zone from the public subnet to the isolated subnet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*YPX4wJsdX20uGYJfNlQmcA.png" /><figcaption>Mutli-AZ RDS in the isolated subnets</figcaption></figure><h4>Step 3: Update the CDK stack</h4><p>Now that you have the actual architecture change, you should update your CDK template to reflect the changes as well. Modify the CDK stack by updating the subnetType to PRIVATE_ISOLATED</p><pre>const subnetType: cdk.aws_ec2.SubnetSelection = { subnetType: cdk.aws_ec2.SubnetType.PRIVATE_ISOLATED };</pre><p>If you want to ensure a closed loop between the CDK template and the actual stack after the CDK template update, do an cdk deploy rds-stack after the change. Because the real subnet group has been updated, there are no materialized changes. cdk deploy rds-stack should return successfully:</p><pre>rds-stack<br>rds-stack: deploying... [2/2]<br><br> ✅  rds-stack (no changes)<br><br>✨  Deployment time: 2.25s<br><br>Outputs:<br>rds-stack.rdsstackrdsname = rds-stack-rds<br>rds-stack.rdsstacksubnetgroupname = rds-stack-rds-subnetgroup</pre><blockquote>If you are skeptical about the CDK state synchronization, try to deploy the stack with const subnetType: cdk.aws_ec2.SubnetSelection = { subnetType: cdk.aws_ec2.SubnetType.PUBLIC }; .</blockquote><blockquote>cdk deploy rds-stack should encounter the same subnet in-use error: UPDATE_FAILED | AWS::RDS::DBSubnetGroup | rdsstackrdssubnetgroup<br>Resource handler returned message: “Some of the subnets to be deleted are currently in use: subnet-03e58f5428463ad26, subnet-06721c9fdaac5f333</blockquote><h3>Conclusion</h3><p>Hosting the Amazon RDS in an isolated environment without internet egress routing offers a range of critical benefits for data security, privacy, and operational integrity:</p><ul><li>Protection from Data Exfiltration: By preventing internet egress routing, the risk of data exfiltration is significantly reduced. Sensitive data remains within the controlled environment, minimizing the chances of accidental or intentional data leakage. This is especially important for compliance with data protection regulations and safeguarding proprietary information.</li><li>Preservation of Operational Integrity: Hosting a database in an isolated environment ensures that the operational integrity of the database is maintained. Unintended internet access, whether due to misconfigurations or vulnerabilities, can lead to unexpected behavior, data corruption, or unauthorized data changes.</li><li>Compliance and Regulatory Alignment: Many industries are subject to stringent compliance regulations that demand strict controls over data handling and storage. Network isolating the database supports compliance efforts such as towards compliance with ISO27001:2013 A.13.1.3.</li><li>Reduction of Attack Surface: An isolated environment reduces the attack surface of the database, making it less susceptible to various types of attacks. Without a direct internet connection, attackers have fewer opportunities to exploit vulnerabilities, inject malicious code, or perform reconnaissance.</li><li>Focus on Internal Threats: While external threats are a concern, internal threats can be equally damaging. Isolating the database limits access to authorized personnel only, reducing the potential for insider threats, accidental data exposure, or data tampering.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54245047a26d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/doit-international/securing-your-data-moving-amazon-rds-from-public-to-isolated-subnet-54245047a26d">Securing Your Data: Moving Amazon RDS from Public to Isolated Subnet</a> was originally published in <a href="https://medium.com/doit-international">DoiT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Site Reliability using AWS Fargate with CDK and Gatling]]></title>
            <link>https://levelup.gitconnected.com/site-reliability-using-aws-fargate-with-cdk-and-gatling-18d340a43588?source=rss-7c96ebaeecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/18d340a43588</guid>
            <category><![CDATA[gatling]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Dr. Richard Kang]]></dc:creator>
            <pubDate>Sat, 03 Apr 2021 15:10:42 GMT</pubDate>
            <atom:updated>2021-04-20T11:50:05.131Z</atom:updated>
            <content:encoded><![CDATA[<p>The reliability of a site requires continuous monitoring to ensure system performance does not deviate from the non-functional requirements because the performance of a system could be affected by new releases or the growth of data.</p><p>One way of measuring the performance is using a client with the capability of simulating the key business activities, and with capabilities to measure the key indicators such as response time or request per second. Gatling is one of the popular libraries commonly used for this purpose.</p><p><a href="https://gatling.io/">Gatling</a> is a SCALA library that leverages the flexible syntax of SCALA to offer Domain Specific Language (DSL) on load testing with key metrics for performance measurement. Gatling uses AKKA for the distributed load agents which offer better resource utilization compare to plain Java threading.</p><p>This article examines three important concepts related to testing: reliability, repeatability, and reproducibility. It then shows you how to use Gatling to set up a performance testing infrastructure using AWS’s Cloud Development Kit (CDK), and gives you pointers to consider when running performance testing against systems of your own.</p><h3>Reliability of the tests</h3><p>In any monitoring and measurement, we need true positive results that we can trust. For example, when the test tool reported a connectivity issue to the web services, we want the result to be <em>true positive</em> that the web service is unavailable and not <em>false positive</em><strong> </strong>due to misconfigured of the bad host that is running the tool.</p><p>Therefore, leveraging serverless architecture to run the testing tool is ideal to ensure the reliability of the execution of the tool.</p><h3>Reproducibility of the tests</h3><p>When issues are reported from the testing, we want to be able to replicate the results to facilitate troubleshooting, or experiment with different factors to reduce any uncertainty. For example, when the QA team found an issue reported by the testing tool, the same result can be replicated by the development team to troubleshooting the same issue reported.</p><p>Automate the building and containerize the testing framework allows us to freeze the code change and pre-defined the library dependencies of the testing framework. With the dockerized image, the same testing can be replicated across teams and environments.</p><h3>Repeatability of the tests</h3><p>We want to run the tests repeatedly when triggered by an event such as before a new release is being deployed, or when triggered by a clock event such as every end of the month to measure the system performance against the Service Level Objectives.</p><p>To run the testings over and over, we need to automate the build of the container image for reproducibility purposes and bring up the infrastructure when triggered, and tear-down when not needed, and repeat in the next trigger.</p><p>To achieve this objective, <a href="https://aws.amazon.com/cdk/">AWS Cloud Development Kit (AWS CDK)</a> offers the functionalities that we can leverage to build the docker image and to provision the necessary infrastructure to achieve the reliability of the testing.</p><h3>Creation of AWS Resources using AWS Cloud Development Kit (AWS CDK)</h3><p>The repository for the CDK and the Gatling can be found in <a href="https://github.com/kangks/distributed_gatling">https://github.com/kangks/distributed_gatling</a>.</p><p>The structure of the repository consists of 2 main folders, cdk/ and gatling/.</p><p>cdk/bin/app.ts is the CDK application written in TypeScript. When invoked with command cdk deploy ecsLoadTestTask, it will create the Stack DistributedECSTaskStack from cdk/lib/ecsTaskStack.ts.</p><p>The Stack uses the <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecr-assets-readme.html#aws-cdk-docker-image-assets">AWS CDK Docker Image Assets API</a>, which builds the Docker image locally withgatling/Dockerfile, and deploys the Docker image to ECR. The Stack will then proceed to provision the AWS Fargate resources along with the other essential infrastructure such as NAT Gateway.</p><p>The deployed architecture will be as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gc6WUGEMwh-Obbtg2OvNHA.png" /></figure><p>In sdk/lib/ecsTaskStack.ts, the Stack DistributedECSTaskStack creates the FargateService with ContainerDefinition that builds the image locally using the API ContainerImage.fromAsset():</p><pre>const containerDef = new ecs.ContainerDefinition(this, &#39;containerDef&#39;, {</pre><pre>[...]</pre><pre>image: ecs.ContainerImage.fromAsset(path.resolve(__dirname, &#39;../../gatling&#39;), {file: &quot;Dockerfile&quot;}),</pre><pre>[...]</pre><pre>})</pre><p>The gatling container uses gatling.sh which is the wrapper script to run the Gatling Highcharts.</p><pre>const containerDef = new ecs.ContainerDefinition(this, &#39;containerDef&#39;, {</pre><pre>[...]</pre><pre>command: [ &quot;gatling.sh&quot;, &quot;-sf&quot;, &quot;/tests/test&quot;, &quot;-s&quot;, &quot;perfTest.simulations.WebServiceSimulation&quot; ],</pre><pre>[...]</pre><pre>})</pre><p>The flag -sf tells the Gatling where to find the simulation class, which is /tests/test as built in the Dockerfile, and the simulation to run with the flag -s .</p><p>For the Gatling container, it also needs the endpoint of the service to be tested, which is defined as web.baseUrl and passed in via JAVA_OPTS :</p><pre>const containerDef = new ecs.ContainerDefinition(this, &#39;containerDef&#39;, {</pre><pre>[...]</pre><pre>environment: {</pre><pre>&quot;GATLING_CONF&quot;: &quot;/tests/test/resources&quot;,</pre><pre>&quot;JAVA_OPTS&quot;: &quot;-Dweb.baseUrl=http://simpl-simpl-1tvem419lsgf7-18442615.us-west-1.elb.amazonaws.com&quot;</pre><pre>},</pre><pre>[...]</pre><pre>})</pre><h3>Gatling</h3><p>A typical Gatling simulation consists of one or many scenarios, and each scenarios invokes one or many requests.</p><p>For example, a simulation to load test a shopping cart service might contain two scenarios, one scenario to search product, and another scenario to add-to-cart.</p><p>For the search product scenario, the request will be to POST a search string into the search service and validate the response from the search service.</p><p>The add-to-cart the scenario might require multiple requests. One request to invoke the authentication service, and store the JWT token in the session. Another request will retrieve the product ID from the search result and the JWT token from the session, and POST to the add-to-cart service, and validate the response. Finally, a validation requests to validate that the product has been added into the cart with a GET call to the cart service.</p><p>Therefore, in this example, we separated the concerns into individual folders, namely,</p><ul><li>gatling/src/test/simulations for all the simulations that setup the scenarios with a load profile</li><li>gatling/src/test/scenarios for all the scenarios by use cases, such as product search</li><li>gatling/src/test/requests for the actual requests, such as authentication request</li></ul><p>When gatling.sh is invoked, it will look in the folder specified with the flag -sf for classes that extend io.gatling.core.scenario.Simulation . If there are more than one simulations found in the folder, and no simulation class specified with the flag -s , gatling.sh will prompt for the selection of which simulation class to run.</p><p>To parameterize the execution of the gatling from the Fargate Tasks, the custom configurator perfTest.config.Configurations will first read the config value from System properties, and if not found, read value from the configuration file defaulted to application.conf in theGATLING_CONF folder.</p><p>The 3 parameters that can be configured through JAVA_OPTS are:</p><ul><li>web.baseUrl which is the endpoint to the system to be tested;</li><li>load.rps which is the concurrent users to simulate the scenario;</li><li>load.durationInSeconds is the duration of the whole simulation.</li></ul><h3>Running the Gatling against a simple web service</h3><p>An example web service using Docker image amazon/amazon-ecs-sample will be used as the system under test.</p><p>The CDK application contains the example web service SimpleFargateWebServicewhich can be deployed with the command cdk deploy simpleWebFargate.</p><p>The stack will be deployed as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpcXuJ0d9SuxAqWCzLiaKQ.png" /></figure><p>Once the stack is created, get the URL from the CloudFormation out using AWS CLI</p><pre>% aws cloudformation describe-stacks --stack-name simpleWebFargate --query &quot;Stacks[0].Outputs[?OutputKey==&#39;SvcUrl&#39;].OutputValue&quot; --output text<br>simpl-simpl-1TVEM419LSGF7-18442615.us-west-1.elb.amazonaws.com</pre><p>The stack-name was defined in the CDK application new SimpleFargateWebService(app, ‘simpleWebFargate’), and the return value will be the endpoint to the Application Load Balancer.</p><p>Next, we will update the endpoint of the simpleWebFargate, in cdk/lib/ecsTaskStack.ts as the web.basedUrl :</p><pre>export class DistributedECSTaskStack extends cdk.Stack {</pre><pre>constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {</pre><pre>[...]</pre><pre>const containerDef = new ecs.ContainerDefinition(this, &#39;containerDef&#39;, {</pre><pre>[...]</pre><pre>environment: {</pre><pre>[...]</pre><pre>&quot;JAVA_OPTS&quot;: &quot;-Dweb.baseUrl=http://simpl-simpl-1tvem419lsgf7-18442615.us-west-1.elb.amazonaws.com&quot;</pre><pre>},</pre><pre>[...]</pre><pre>})</pre><pre>[...]</pre><pre>}</pre><pre>}</pre><p>With the web.baseUrl updated according to the output of the simpleWebFargate stack, we can deploy the stack using the command cdk deploy ecsLoadTestTask to deploy the DistributedECSTaskStack.</p><p>Once the stack ecsLoadTestTask is deployed, the Fargate Task will run. The log output from the Gatling will be available in the CloudWatch log.</p><p>To inspect the Gatling output, we can use the AWS CLI to tail the LogGroup perfTest , which was defined when creating the <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.AwsLogDriver.html">ECS AWSLogDriver</a>:</p><pre>const logging = new ecs.AwsLogDriver({</pre><pre>[...]</pre><pre>logGroup: new log.LogGroup(this, &#39;gatlingLogGroup&#39;, {</pre><pre>logGroupName: &#39;perfTest&#39;,</pre><pre>[...]<br>})</pre><pre>})</pre><p>The AWS CLI to run is aws logs tail perfTest . If the execution was successful, you should be able to see that the assertion was passing:</p><pre>2021-04-03T15:06:43.886000+00:00 gatling/containerDef/8b703ac477474209b0b1ef076c90fd56 Global: percentage of successful events is greater than 99.0 : true<br>2021-04-03T15:06:43.886000+00:00 gatling/containerDef/8b703ac477474209b0b1ef076c90fd56 Global: max of response time is less than 5000.0 : true</pre><p>The assertions in the Gatling simulation are</p><pre>package perfTest.simulations</pre><pre>[...]</pre><pre>class WebServiceSimulation extends Simulation {</pre><pre>[...]</pre><pre>setUp(</pre><pre>[...]</pre><pre>)</pre><pre>.assertions(</pre><pre>global.successfulRequests.percent.gt(99),</pre><pre>global.responseTime.max.lt(5000),</pre><pre>)</pre><pre>[...]</pre><pre>}</pre><h3>Conclusions</h3><p>In this article, we covered the basic components for a Gatling test, starting from the entry point of a Simulation, which invokes Scenarios that consists of multiple Requests.</p><p>We created a simple Gatling simulation to test on a web service and build it into a Gatling Docker image that allows the load profile to be parameterized through the Docker runtime as environment variables, which are the URL of the web service, concurrent requests per second, and duration of the pressure.</p><p>We ran the load test using AWS Fargate to leverage serverless computing so that we can focus on the test strategy. For example, to ensure the system performance is within the non-functional requirements, a 1-hour load test with a small concurrent load can be scheduled to run every end-of-day. On the other hand, a large concurrent load that spans across multiple AWS Fargate tasks can be used as a release check before any major release to the production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18d340a43588" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/site-reliability-using-aws-fargate-with-cdk-and-gatling-18d340a43588">Site Reliability using AWS Fargate with CDK and Gatling</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>