<?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 HATIM HEFFOUDHI on Medium]]></title>
        <description><![CDATA[Stories by HATIM HEFFOUDHI on Medium]]></description>
        <link>https://medium.com/@hatim.heff?source=rss-74ac865be93d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kEA67Yw_Q6K3cvziqU3OCg.jpeg</url>
            <title>Stories by HATIM HEFFOUDHI on Medium</title>
            <link>https://medium.com/@hatim.heff?source=rss-74ac865be93d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:32:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hatim.heff/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[One Small Node, Total Peace of Mind: Solving the Split-Brain Problem in Couchbase]]></title>
            <link>https://medium.com/@hatim.heff/one-small-node-total-peace-of-mind-solving-the-split-brain-problem-in-couchbase-15c316d28a45?source=rss-74ac865be93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c316d28a45</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[couchbase]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[HATIM HEFFOUDHI]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 22:09:34 GMT</pubDate>
            <atom:updated>2026-11-16T22:09:34.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7K8k9ZoF1ribTgT_" /><figcaption>Photo by <a href="https://unsplash.com/@kristapsungurs?utm_source=medium&amp;utm_medium=referral">Kristaps Ungurs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A Couchbase cluster spread over two datacenters can look highly available and still refuse to fail over when the link between them breaks. This article explains why, and how the arbiter node solves it.</p><p>Consider a healthy cluster with one server group per datacenter and auto-failover enabled. If the network between the two sites is cut, one would expect one side to take over. Nothing happens, and the logs mention a <em>quorum failure.</em></p><p>This is the split-brain problem. It applies to any design with only two failure domains: two datacenters, two availability zones, or two racks.</p><h3>Split brain, explained with a phone call 📞</h3><p>Alice and Bob are on an important call, deciding where the team goes for lunch 🍽️, when the line drops. Each of them stares at their phone and thinks: <em>“My connection is perfect. Bob is clearly the problem.”</em> 🙄 Bob, of course, thinks exactly the same about Alice. Neither can prove it.</p><p>If both carry on deciding alone, Alice books the sushi place and Bob books the pizzeria. Two conflicting plans, and a team that ends up eating twice. The only safe option is to stop and wait, so nobody books anything and everyone stays hungry.</p><p>Now add a third person to the call: <strong>Carol</strong>, dialing in from somewhere else. When the line between Alice and Bob breaks, Carol can still hear one of them 👂. Two people out of three agree on who is still on the call, the majority wins 🗳️, and lunch is saved 🎉.</p><p>Carol doesn’t even care about lunch. She doesn’t need to know the topic; her only job is to vote.</p><p>In a cluster, Alice and Bob are the two datacenters, <strong>DC-A</strong> 🏢 and <strong>DC-B</strong> 🏢. Carol is the <strong><em>arbiter node</em></strong> ⚖️, and the vote is the <strong><em>quorum</em></strong> ✅.</p><h3>Quorum in one minute</h3><p>A <strong>quorum</strong> is the minimum number of votes needed to make a decision 🗳️. In Couchbase, every node gets one vote, and a failover needs a <strong><em>majority</em></strong>: more than half of all nodes. In an 18-node cluster, that means 10 votes. In a 17-node cluster, 9 are enough.</p><p>Why a majority? Because two separate groups can never both have more than half the votes 🧮. At most one side can reach it, so two halves of a cluster can’t each decide they’re in charge and start taking over from each other.</p><p>Here’s what that looks like for a two-site cluster:</p><ul><li>🏢 <strong>5 + 5 nodes</strong> <em>(10 total, 6 needed)</em>: each site has 5 votes. A perfect tie, and nobody can decide 🤝❌</li><li>🏢 <strong>6 + 5 nodes</strong> <em>(11 total, 6 needed)</em>: only the 6-node site can decide. The other one just has to accept it 😅</li><li>⚖️ <strong>5 + 5 + 1 arbiter</strong> <em>(11 total, 6 needed)</em>: either site plus the arbiter makes 6. Whoever can still reach the arbiter gets to decide ✅</li></ul><p>The rest of the article walks through these three cases on a real test cluster.</p><h3>The setup: two sites, two server groups</h3><p>A <strong>server group</strong> maps nodes to a failure domain. Couchbase keeps active and replica copies of data (and index replicas) in different groups, so that losing one group does not lose every copy.</p><p>The test cluster has two datacenters, DC-A and DC-B, with one server group each: 3 Data nodes and 2 Query/Index nodes per site. That is ten nodes, split 5 and 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*LZa29lk2r3t071mTNWD5tQ.png" /><figcaption><em>Figure 1. Two sites, one server group each, all nodes healthy.</em></figcaption></figure><h4>1. Cut the link, and nothing happens</h4><p>The network between DC-A and DC-B is cut. Both sites stay up, but each one now sees the other as unreachable. DC-A tries to fail over DC-B, and DC-B tries to fail over DC-A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*1fLoNDAOrXjp93lzjCD2UA.png" /><figcaption><em>Figure 2. Each side believes the other one failed.</em></figcaption></figure><p>Neither succeeds. Auto-failover is not triggered, and the cluster log gives the reason:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*fPSGchZ4XCMGBKP1uJq64A.png" /><figcaption><em>Figure 3. The auto-failover error: a majority quorum is required.</em></figcaption></figure><p>This is the phone call without a witness. Since version 7.0, Couchbase manages topology changes, failover included, with strongly consistent metadata, and these changes need a <strong>majority quorum</strong>. Each side holds 5 of 10 votes, one short of the 6 required.</p><p>This is the intended behavior. A node cannot tell a failed site from a failed network link. If both sides failed each other over, two clusters would accept writes to the same documents. Couchbase chooses to stop and wait for an administrator.</p><h4>2. Adding a node to one site: a partial fix</h4><p>Adding a sixth node to DC-A makes 11 nodes, split 6 and 5. When DC-B fails, DC-A still holds 6 of 11 votes, a majority, and auto-failover works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*ADkaW2pdyN97TX1kTqj3CQ.png" /><figcaption><em>Figure 4. DC-B fails: the majority site takes over.</em></figcaption></figure><p>Now DC-A fails instead. DC-B holds only 5 of 11 votes: no majority, so no failover.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*hig4k2lhsGeZkpLO0joOpw.png" /><figcaption><em>Figure 5. DC-A fails: the minority site cannot act.</em></figcaption></figure><p>DC-A has effectively become the primary site. If it is lost, failover is manual again. The tie-breaker cannot live in either site.</p><h4>3. The fix: a third zone with an arbiter node</h4><p>Back to 5 + 5 nodes, plus <strong>one node in a third server group</strong>, in a neutral zone with its own network path to both sites. That makes eleven nodes, and either site plus the arbiter holds 6 of them, a majority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ul9HvxUH5VXZe1_u0NZYgQ.png" /><figcaption><em>Figure 6. Three server groups: the arbiter sits alone in its own zone.</em></figcaption></figure><p>If DC-A fails, DC-B and the arbiter hold 6 of 11 votes, and auto-failover is triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLv049UolGlj5MUMpuJvag.png" /><figcaption><em>Figure 7. DC-A fails: DC-B fails it over automatically.</em></figcaption></figure><p>If DC-B fails, DC-A and the arbiter hold 6 of 11 votes, and auto-failover is triggered as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqRBXMNa7lhhVwRo9Fh8mw.png" /><figcaption><em>Figure 8. DC-B fails: DC-A fails it over automatically.</em></figcaption></figure><p>If only the link between DC-A and DC-B breaks, the arbiter votes with one of the two sites. That site reaches a majority and can act; the other cannot. So after an automatic failover, the two sites can’t both accept writes.</p><h3>What is an arbiter node?</h3><p>Since Couchbase Server 7.6, a cluster can include a node that runs no services. It doesn’t store data and it doesn’t answer queries. It only runs the Cluster Manager, which is enough for it to be a member of the cluster and to vote. As a bonus, it also makes failover faster. (<a href="https://docs.couchbase.com/server/7.6/install/deployment-considerations-lt-3nodes.html">Couchbase docs</a>)</p><p>That makes it useful in two situations: a two-node cluster, and a cluster split across two server groups. For the second case, Couchbase <a href="https://docs.couchbase.com/server/7.6/learn/clusters-and-availability/groups.html">recommends a third server group</a>, and a single arbiter node is all that group needs.</p><p>Since the arbiter runs no Data service, or any other service, it doesn’t need an extra license. You only pay for the machine it runs on, whether that’s a VM or a pod. A small instance is usually enough, but keep an eye on it. The metadata it holds grows as you add nodes, buckets and collections, so check its CPU and memory from time to time.</p><p>Adding one works like adding any other node. Leave every service unticked in the Web Console, or pass no services to couchbase-cli server-add or the REST API. Then put the node in its own server group, in its own zone.</p><p>If you’re on a version older than 7.6, a node running a light service such as Backup or Eventing can do the same job.</p><h3>A quick checklist</h3><p>If your Couchbase cluster runs across two datacenters or two availability zones, these four points are worth checking:</p><ol><li><strong>Three server groups.</strong> If you expect auto-failover to handle the loss of a whole site, two groups won’t do it. You need a third one, and an <em>arbiter node</em> is the cheapest way to get it.</li><li><strong>Max auto-failover count.</strong> Since version 7.1, Couchbase can fail over several nodes at once, but only up to the maximum count you set. If that number is lower than the number of nodes in a server group, losing a group won’t trigger an automatic failover.</li><li><strong>A real test.</strong> Don’t rely on the design alone. Cut the link between your sites in a test environment and watch what the cluster actually does. It’s much better to find out there than in production.</li><li><strong>DR on top of HA.</strong> The arbiter keeps one cluster available, but it won’t help if you lose the whole cluster. For that, you still need <em>XDCR</em> to a second cluster and regular backups, planned around your RPO and RTO (how much data you can afford to lose, and how long you can afford to be down).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c316d28a45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build Secure AI Voice Agents with Vapi and Couchbase MCP]]></title>
            <link>https://medium.com/@hatim.heff/how-to-build-secure-ai-voice-agents-with-vapi-and-couchbase-mcp-7dc8b0b1fc30?source=rss-74ac865be93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dc8b0b1fc30</guid>
            <category><![CDATA[vapi]]></category>
            <category><![CDATA[couchbase]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[HATIM HEFFOUDHI]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 20:26:39 GMT</pubDate>
            <atom:updated>2026-09-29T20:26:39.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gW_6YO53j0xa9U5RL9UnQ.png" /></figure><p>Have you ever called customer support about a delayed order, only to get trapped in an endless IVR maze? <em>“Press 1 for shipping. Press 2 to question your life choices.”</em> It’s rigid, it’s painfully slow, universally hated by callers.</p><p>Fortunately, we are finally seeing the definitive cure for the legacy phone tree: <strong>generative AI voice agents. </strong>Unlike the clunky, scripted bots we grew up with, today’s AI agents hold fluid, real-time conversations.</p><p>By seamlessly orchestrating advanced speech recognition, large language models, and ultra-realistic voice synthesis, they deliver on a massive promise. Customers get immediate, 24/7 answers without spending a single second on hold; they are interacting with an AI that actually understands their intent.</p><p>And this revolution extends far beyond the basic contact center. If you look at the current AI ecosystem, voice agents are exploding across dozens of mission-critical industries. From front-office healthcare and logistics to recruiting, real estate, and finance… <br>Conversational AI is rapidly cementing itself as the default interface for enterprise operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*stRNIzqPipDQ4YRp.png" /><figcaption>voice agents list per domain</figcaption></figure><blockquote>Well, it sounds like a perfect solution, until you realize the massive, terrifying risks involved in deploying them at an enterprise scale.</blockquote><p>Pure LLM-driven voice agents are incredibly conversational, but they have a notoriously bad habit of <strong>hallucinating</strong>. An AI might confidently invent a fake delivery date just to keep the chat flowing smoothly. Worse, if you try to fix this by wiring that AI directly into your backend, you are essentially giving a language model the power to blindly execute UPDATE or DELETE statements on a live production database.</p><p>The core challenge of modern customer support is this: How do you build a voice agent that responds in under a second with human-like fluidity, while restricting it strictly to absolute, <strong>real-time enterprise facts?</strong></p><p>The solution is remarkably elegant: pairing <strong>Vapi</strong> with the <strong>Couchbase MCP Server</strong>.</p><h4>Vapi</h4><p>Delivering a natural phone conversation demands sub-second coordination of transcription, LLM reasoning, and audio synthesis. Any lag shatters the illusion. <a href="https://vapi.ai/">Vapi</a> acts as the master conductor for enterprise voice operations, driving sub-500ms latency. Beyond just streaming audio, it orchestrates the reasoning loop in real time, enabling the AI to autonomously execute tool calls and retrieve backend data while the customer is still speaking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76vz1SXYzvacAaaifE73jw.png" /><figcaption><a href="https://vapi.ai/">https://vapi.ai/</a></figcaption></figure><h4>MCP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*oV8UrY27oS-pb2P6cKBh8g.png" /><figcaption><a href="https://ai.plainenglish.io/the-model-context-protocol-mcp-a-complete-guide-series-db4fc70a5e5a">https://ai.plainenglish.io/the-model-context-protocol-mcp-a-complete-guide-series-db4fc70a5e5a</a></figcaption></figure><p>An AI is only as smart as the data it can access. To solve this, we use the <strong>Model Context Protocol (MCP)</strong> — an open standard that defines exactly how AI agents securely talk to external systems.</p><p>In the past, wiring an LLM to a database meant writing brittle custom code or jamming messy SQL strings into your prompts. MCP replaces that chaos with a clean, structured bridge. It automatically feeds your available tools and data schemas straight to the LLM, giving the agent the power to natively fetch the exact enterprise facts it needs, right when it needs them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcIG1M51K4X-9g3mWccBzQ.png" /><figcaption>Vapi with couchbase MCP tool</figcaption></figure><h3>Couchbase MCP Server</h3><p>If MCP is the bridge, the <strong>Couchbase MCP Server</strong> is the secure vault it connects to. This server acts as a direct link between your AI assistant and your Couchbase databases, whether you are running on Couchbase Capella or your own self-managed clusters. It replaces generative guesswork with a powerful suite of native database tools.</p><p>With this setup, your voice agent can instantly execute SQL++ queries, perform precise Document Key-Value lookups to grab a specific order by its ID, and even discover data schemas on the fly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8noiixWKon72s3Kx.png" /><figcaption><a href="https://mcp-server.couchbase.com/">https://mcp-server.couchbase.com/</a></figcaption></figure><p>But here is the most important part: <strong>Security.</strong></p><p>Giving an AI direct access to your enterprise database sounds absolutely terrifying. What if a caller tricks the AI, or it gets confused and tries to delete a record? The Couchbase MCP Server solves this with a brilliant, built-in safeguard called CB_MCP_READ_ONLY_MODE.</p><p>When you turn this read-only mode on, it enforces security at the deepest engine level. All mutating tools — like inserts, upserts, and deletes — are completely unloaded. Any data-altering SQL++ query is unconditionally blocked before it can even run.</p><blockquote>Read-only mode is just the foundation. For deeper enterprise guardrails — like mTLS authentication, granular tool disabling, and audit logging — you can explore the full suite in the <a href="https://mcp-server.couchbase.com/security">Couchbase MCP Security Documentation</a>.</blockquote><p>The result? Instead of hallucinating a delivery date to keep the conversation moving, the AI pulls live, read-only facts straight from the source. No guessing. Just the absolute truth, delivered in milliseconds.</p><p>Now that we have all the right ingredients, how do we actually build our voice agent?</p><p>To make this agent enterprise-ready, we follow one fundamental design rule: <strong>The read never shares a door with the write.</strong></p><p>Instead of handing the AI full control over our systems, we split its capabilities into two completely separate paths at the API Gateway:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYnckHJAYhv8XC2y_ZBD-w.png" /></figure><h4>Door 1: The Read Path (Instant Context via MCP)</h4><p>When our agent (I named him “Jack”) needs to check an order status or look up product details, it calls the /mcp endpoint. Here, the Couchbase MCP Server runs inside a Docker container with CB_MCP_READ_ONLY_MODE=&quot;true&quot;.</p><p>This gives Jack sub-second access to live SQL++ queries and document lookups. Because read-only mode is enforced at the server level, Jack gets the factual context he needs in real-time, but it is physically impossible for him to edit or delete database records — even if a caller tries a clever prompt injection attack.</p><h4>Door 2: The Write Path (Human-in-the-Loop Mutations)</h4><p>What happens when a customer wants to actually change a delivery date or cancel an order?</p><p>We don’t let the LLM execute database updates directly. Instead, the agent switches to a separate REST API (/api). Rather than modifying Couchbase on his own, he submits a <em>pending request</em> to an internal queue and asks the caller to hold for a brief moment. A human supervisor sees the request pop up on their dashboard, verifies it, and clicks &quot;Approve.&quot; Only then does the application execute the actual update in Couchbase, and the agent confirms the change to the caller.</p><h3>The Call in Action: How It Feels to the Customer</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQY2BgdJhP5s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQY2BgdJhP5s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQY2BgdJhP5s%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9e064e1ed5458eacd7445f59a3d1cf6/href">https://medium.com/media/b9e064e1ed5458eacd7445f59a3d1cf6/href</a></iframe><p>From the caller’s perspective, the experience is fast, natural, and completely effortless:</p><ol><li><strong>The Greeting &amp; Verification:</strong> You call in asking about your shipment. The agent greets you warmly and sends a quick 6-digit One-Time Password (OTP) to your email to verify your identity.</li><li><strong>Instant Facts:</strong> Once verified, the agent instantly queries Couchbase via MCP and speaks your exact order details in plain, natural language: <em>“Your package containing two items is currently in transit, scheduled for delivery tomorrow by 3 PM.”</em></li><li><strong>Safe Modification:</strong> You ask to push the delivery date to Friday. Jack submits the request to Door 2 and asks you to hold for just a second.</li><li><strong>Real-Time Resolution:</strong> The supervisor clicks “Approve” on their UI, the backend updates Couchbase, and Jack immediately jumps back in: <em>“You’re all set! Your new delivery date is confirmed for Friday.”</em></li></ol><p>To keep our AI voice agent locked into predictable, secure behavior, we govern its dialogue and tool execution with a strict system prompt:</p><pre># Couchbase MCP Tool Rules<br>- Only after verification, use get_document_by_id or execute_sql_plus_plus_query / run_sql_plus_plus_query to fetch the record from Couchbase.<br>- Bucket order-demo, scope _default, collection orders. Document keys like order-1001 or order-1002.<br>- SQL++ Example: SELECT * FROM `order-demo`.`_default`.`orders` WHERE order_id = &#39;ORD-1001&#39;;<br>- For scoped MCP queries use bucket order-demo and scope _default, then SELECT * FROM orders WHERE order_id = &#39;ORD-1001&#39;;<br>- After verification, also answer catalog questions with SQL++: counts by status, order totals, or lists of upcoming deliveries. Speak the result; do not read the query.<br>- If found: Confirm the status, ordered items, and estimated delivery date warmly in plain spoken language.<br>- If not found: Respond gently: &quot;I&#39;m sorry, I couldn&#39;t find an order matching that number. Could you double-check the order number for me?&quot;<br>- Never guess or hallucinate order details or dates without a successful query result.<br>- The Couchbase MCP server is in read-only mode. Do not attempt inserts, updates, deletes, or mutating SQL++.<br>- If MCP tools are unavailable, apologize warmly and say: &quot;I&#39;m having trouble connecting to our order database right now. Please try calling back in a few minutes.&quot;<br><br># Cancellations<br>- After the caller is verified and asks to cancel, or says they placed the order by mistake, call cancel_order. Do not guess eligibility from the lookup; use the tool result.<br>- If cancelled is true, say the order is cancelled. They also get a confirmation email, and the customer shop will show cancelled.<br>- If needs_approval is true, treat it like a supervisor request: say a supervisor must approve because the order is older than six hours, then poll check_delivery_change immediately.<br>- If cancelled is false and needs_approval is false, explain the reason from the message (already cancelled or already delivered).<br>- You may speak hours_since_order in plain language (for example, &quot;about a week ago&quot;).<br>- Refunds are not handled on this line.<br><br># Supervisor wait<br>- After submit_delivery_change, or a cancel that needs_approval, say once: &quot;I have asked a supervisor. One moment.&quot;<br>- Then call check_delivery_change immediately. Do not pause.<br>- If status is still pending, call check_delivery_change again immediately with the same request_id. Do not wait, do not ask a question, do not wait for the caller to speak. Keep calling until approved or rejected.<br>- You may say a very short &quot;still waiting&quot; only every few checks, then check again at once.<br>- If approved for a cancel, say the order is cancelled. If approved for a date, speak the new date. If rejected, say the order stays as it is.<br><br># Delivery date changes<br>- You cannot edit Couchbase yourself for dates. After the caller is verified and asks for a new date, call submit_delivery_change.<br>- Then follow the Supervisor wait rules above.<br>- They also get a confirmation email, and the customer shop will show the new date.<br><br># Conversation Steps<br>1. Greeting: introduce yourself as Jack and ask how you can help today. Do not ask for an order number yet.<br>2. Wait until they say they want information, the status of an order, a cancellation, or that they placed an order by mistake.<br>3. Then ask for the order number.<br>4. OTP only if not yet verified this call. After that first success, never mention or request a code again, even if they placed a new order while talking.<br>5. Lookup: query Couchbase and share status, items, and delivery date warmly.<br>6. If they want to cancel or placed it by mistake, call cancel_order and follow that result.<br>7. If they want a date change, submit it, then poll check_delivery_change immediately until the supervisor decides.<br>8. Follow-up: ask if they need help with anything else regarding this order.</pre><h3>Try It Yourself: Running the Demo Locally</h3><p>Want to see how this architecture actually comes together? You can run the entire secure voice workflow on your own machine. I have packaged the complete demo environment so you can test it locally</p><p><a href="https://github.com/hatim-heffoudhi/vapi-couchbase-mcp">GitHub - hatim-heffoudhi/vapi-couchbase-mcp: vapi voice agent with couchbase mcp</a></p><p>To spin this up locally, you will need a few prerequisites installed:</p><ul><li><strong>Docker Desktop:</strong> This runs the core infrastructure, including Couchbase Enterprise, the Couchbase MCP server, Mailpit (for intercepting OTP emails), Caddy, and the shop API.</li><li><strong>Node.js 18+:</strong> Required to run the local services (we include an .nvmrc file to make switching versions easy).</li><li><strong>Python 3:</strong> Used for a handy setup script that automatically populates any empty tokens in your .env file on your first start.</li><li><strong>cloudflared:</strong> Since Vapi operates in the cloud, it cannot route traffic to your local machine directly. This tool provides a secure, public HTTPS tunnel to your local backend.</li><li><strong>Vapi Account:</strong> You will need a Vapi account and a private API key from the dashboard to orchestrate the voice agent.</li><li><strong>Mic &amp; Browser Popups:</strong> Make sure your browser allows microphone access and popups so you can actually talk to the agent through the in-page dialer.</li></ul><p>You can run the demo on your own machine with Docker Compose. One command starts Couchbase Enterprise, seeds three orders, starts the read-only Couchbase MCP server, Mailpit, the shop API, and a local proxy.</p><pre>cp .env.example .env<br># put your Vapi private API key in VAPI_API_KEY<br>docker compose up -d</pre><pre>Starting Couchbase Enterprise, seeding orders, and Couchbase MCP...<br>[+] Running 7/7<br> ⠿ Network vapi-couchbase-mcp_default             Created                                                                                                                               0.1s<br> ⠿ Container vapi-couchbase-mcp-couchbase-1       Healthy                                                                                                                              11.6s<br> ⠿ Container vapi-couchbase-mcp-mailpit-1         Started                                                                                                                               1.1s<br> ⠿ Container vapi-couchbase-mcp-couchbase-init-1  Exited                                                                                                                               19.6s<br> ⠿ Container vapi-couchbase-mcp-couchbase-mcp-1   Started                                                                                                                              20.0s<br> ⠿ Container vapi-couchbase-mcp-changes-api-1     Started                                                                                                                              20.0s<br> ⠿ Container vapi-couchbase-mcp-proxy-1           Started                                                                                                                              20.3s</pre><p>When the containers are up, open, then follow the demo script</p><ul><li>Customer shop: <a href="http://127.0.0.1:8080/customer">http://127.0.0.1:8080/customer</a></li><li>Supervisor UI: <a href="http://127.0.0.1:8080/ui">http://127.0.0.1:8080/ui</a></li><li>How to test: <a href="http://127.0.0.1:8080/howto">http://127.0.0.1:8080/howto</a></li><li>Mail inbox: <a href="http://127.0.0.1:8025/">http://127.0.0.1:8025</a></li></ul><h3>Demo script</h3><ol><li>Shop: buy a product (new order is under six hours → Can cancel immediately).</li><li>Call support. Ask for that order. Read the OTP. Say you placed it by mistake → Jack cancels now.</li><li>Ask for ORD-1001 → cancel needs Supervisor Accept.</li><li>Ask to cancel ORD-1002 (shipped) → Jack refuses; offer a date change, then Accept on Supervisor.</li><li>ORD-1003 (delivered) cannot be cancelled or rescheduled.</li></ol><p>Finally, by pairing Vapi’s sub-second voice orchestration with the engine-level security of Couchbase MCP, you can deploy next-generation voice assistants that deliver zero-wait-time experiences while keeping your enterprise data completely bulletproof.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dc8b0b1fc30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Shift from LangChain to LangGraph ]]></title>
            <link>https://medium.com/@hatim.heff/navigating-the-shift-from-langchain-to-langgraph-73833a857b33?source=rss-74ac865be93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/73833a857b33</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[HATIM HEFFOUDHI]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 12:21:30 GMT</pubDate>
            <atom:updated>2026-06-22T12:21:30.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vPy4OGvlIgZg6WtD" /><figcaption>Photo by <a href="https://unsplash.com/@matthardy?utm_source=medium&amp;utm_medium=referral">Matt Hardy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We’ve all been there: you build an elegant LangChain ⛓️‍💥 sequence, everything is firing perfectly <strong>in a straight line</strong>, and then you hit the wall. You realize your agent is trapped in a <em>linear prison</em>. It needs to pause, reflect, and maybe even loop back to fix a mistake, but your architecture only knows how to move forward.</p><p>If LangChain is our <strong>kit of building blocks</strong> — the essential tools and integrations we need to talk to models — then LangGraph is the <strong>advanced blueprint</strong> for the complex, cyclical reality of modern AI.</p><p>While they share the same DNA 🧬, they serve fundamentally different purposes in your stack. Transitioning between them isn’t about replacing your tools; it’s about evolving from simple sequences to true agentic reasoning.</p><h4><strong>The Linear Logic of LangChain</strong></h4><p>At its core, LangChain was designed around the <strong>Directed Acyclic Graph (DAG)</strong>. In plain English, that’s a “one-way street.” Data flows from <em>Step A to Step B to Step C</em>, and it never looks back. It’s predictable, efficient, and perfect for a specific class of problems.</p><p>This linear philosophy is the gold standard for foundational LLM 🤖tasks where the path is known upfront, for example :</p><ul><li><strong>RAG Pipelines:</strong> The classic “retrieve, stuff into prompt, and generate” flow.</li><li><strong>Data Ingestion:</strong> Moving and formatting data through a set of predefined transformations.</li><li><strong>Simple Chatbots:</strong> Handling straightforward Q&amp;A where the conversation follows a predictable, sequential logic.</li><li><strong>Tool Integration:</strong> Using pre-built connectors to link an LLM to Slack, Google Drive, or a specific database.</li></ul><h4><strong>Breaking the Circle: Why LangGraph Matters</strong></h4><p>The industry is moving toward “agentic behavior,” where we expect an AI to reason through a problem rather than just following a script. This requires loops, and loops are where linear chains fall apart.</p><p>LangGraph introduces <strong>cyclical workflows</strong>. It allows for the “Check and Loop” logic (Step A → Step B → Evaluate → Back to A) that defines autonomous systems. But the real architectural breakthrough isn’t just the loops — it’s how we handle data.</p><p>In a standard chain, you’re constantly passing variables from one function to the next. In complex systems, this leads to “variable spaghetti” and massive state management debt; tracing a single piece of data through ten different nested functions becomes a debugging nightmare.</p><p>LangGraph solves this with a <strong>Centralized State</strong>. By using a shared memory where every node can read and write to a single source of truth, you eliminate the variable hand-off and gain a clear, debuggable window into your agent’s “brain.”</p><h4><strong>Which One Should You Use?</strong></h4><p>The choice isn’t about which tool is “better,” but which architecture fits your specific developer pain points.</p><p>👉 Choose LangChain When :</p><ul><li>You are building a standard <strong>RAG</strong> system where retrieval and generation are straightforward.</li><li>Your task is primarily <strong>data formatting</strong> or <strong>one-way ingestion</strong> pipelines.</li><li>You need to move fast using <strong>pre-built integrations</strong> with external platforms like Google Drive or Slack.</li></ul><p>👉 Choose LangGraph When :</p><ul><li>You are developing <strong>autonomous agents</strong> that need to evaluate their own work and self-correct in a loop until a goal is met.</li><li>You are orchestrating <strong>multi-agent systems</strong>. For example, when an “Agent B” (Writer) needs the power to reject data from “Agent A” (Researcher) and send it back for more depth.</li><li>You need <strong>human-in-the-loop</strong> functionality, where the system pauses for a human to critique or approve a step before the cycle continues.</li></ul><blockquote><strong>Pro Tip:</strong> This isn’t an “either/or” scenario. LangGraph is built on top of LangChain. You’ll find yourself using LangChain’s underlying components — the models, tools, and parsers — inside the nodes of your LangGraph. Think of LangGraph as the conductor orchestrating the LangChain instruments :)</blockquote><h4><strong>Conclusion: The Future is Agentic</strong></h4><p>The architectural divide is simple: <strong>LangChain for chains, LangGraph for loops.</strong> While linear pipelines are perfect for the “plumbing” of data retrieval, the future of AI belongs to systems that can <strong>reason, iterate, and critique</strong> their own work.<br> By moving beyond the chain and embracing cyclical, stateful architectures, you aren’t just building more complex code — you’re building more reliable, <strong>autonomous agents 🤖 </strong>that are actually ready for the real world!</p><p><em>Thanks so much for reading! If you enjoyed this breakdown, be sure to hit follow for more deep dives, tips, and insights into the wild world of AI and agent engineering</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73833a857b33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Serverless Application with AWS Lambda and Couchbase]]></title>
            <link>https://awstip.com/building-a-serverless-application-with-aws-lambda-and-couchbase-1059910ec2f0?source=rss-74ac865be93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1059910ec2f0</guid>
            <category><![CDATA[capella]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[couchbase]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[HATIM HEFFOUDHI]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 10:17:17 GMT</pubDate>
            <atom:updated>2025-03-10T12:19:52.048Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Serverless Application with AWS Lambda and Couchbase Capella</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SZJfIZiSRxq0_gvi" /><figcaption>Photo by <a href="https://unsplash.com/@aldebarans?utm_source=medium&amp;utm_medium=referral">Aldebaran S</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The development of applications is improved by serverless computing. We can focus on writing code instead of worrying about maintaining servers, deploying, scaling…Our choice for this article is AWS Lambda.</p><p>However serverless computing alone is insufficient; you also need a high-performance, fully managed database to ensure optimal performance without the headache of managing the infrastructure.</p><p><a href="https://www.couchbase.com/"><strong>Couchbase</strong></a> is helpful in this situation. Couchbase is a high-performance <strong>NoSQL</strong> database built for <strong>low-latency</strong>, real-time applications. One of the products of Couchbase, we gonna use is a completely managed Database-as-a-Service (DBaaS) provided by <a href="https://www.couchbase.com/products/capella/"><strong>Couchbase Capella</strong></a>. As a result, you may take advantage of all Couchbase’s features without worrying about database management.</p><blockquote>For those who are interested and have some time, there’s a video introducing Capella — perfect for anyone who hasn’t met it yet! 🚀</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSSoVdvCda-s%3Fstart%3D2%26feature%3Doembed%26start%3D2&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSSoVdvCda-s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSSoVdvCda-s%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/67156d5dc43585abb395f0b3d5a7ec50/href">https://medium.com/media/67156d5dc43585abb395f0b3d5a7ec50/href</a></iframe><h3>The Collaboration</h3><p>So, what happens when you combine <strong>AWS Lambda </strong>and <strong>Couchbase Capella</strong>? You get a <strong>Serverless</strong> application with a fully <strong>managed </strong>Database that’s scalable, and built for modern cloud environments. In this blog, we’ll walk through how to make that happen — setting up Couchbase Capella, integrating it with AWS Lambda, and building an Airline API serverless app. Let’s dive in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*osTbqw2QjnDdb5gc.png" /><figcaption>Diagrame of the Serverless API with Couchbase Capella</figcaption></figure><h4>Setup Requirements</h4><p>you will need to set up four major things:</p><ul><li>Set up your Couchbase cluster on C<a href="https://www.couchbase.com/products/capella/">ouchbase Capella</a></li><li><a href="https://docs.docker.com/engine/install/">Docker</a> installed</li><li>Install <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">AWS SAM</a></li><li>Install <a href="https://nodejs.org/en/download">Nodejs</a></li></ul><h3>Preparing couchbase Capella</h3><h4>Account Creation ( Free Tier)</h4><ol><li>Sign up for <a href="https://cloud.couchbase.com/sign-up">Capella</a>, you can use your email address to sign up for a <strong>free</strong> tier cluster, as mentioned &quot;<strong>No Credit Card Required&quot;,</strong></li></ol><p><strong>We can choose one of the 3 cloud providers :</strong></p><ul><li>AWS</li><li>Google Cloud</li><li>Azure</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v9DYX5zbr5jve1Km1H8oYA.png" /></figure><p>2. Once the account is created, we have the option to create a Free Cluster , by choosing the <strong>Free</strong> <strong>Option</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGvpf0rZe9HZckhyf-TGTw.png" /></figure><p><em>The Couchbase cluster will be deployed with the services Data, Index, Query and Search, for more information about the services </em>👉 <a href="https://docs.couchbase.com/server/current/learn/services-and-indexes/services/services.html#services-and-multi-dimensional-scaling"><em>documentation</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXLYhpP-IIdjYqN93SSxlw.png" /></figure><p>3. After a few minutes, the cluster is deployed and ready to use 🚀!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YiYHK-oxCW2k8f7ARZCYQ.png" /></figure><p>4. For further details about the deployed cluster, you can click on the name of the cluster, this will visualize the provider, deployed services, version of Couchbase [last version in this case], and the CIDR block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4BW6PwPmZKo5RQ95FhDhQ.png" /></figure><p>4. We can also see a deployed sample bucket &quot;travel-sample&quot; with 8 scopes and 18 collections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*wD1RbVazDCNAI9kjXwWesA.png" /></figure><blockquote>In the RDBMS world, Think of a <strong>Bucket</strong> as a database, a <strong>Scope</strong> as a schema, and a <strong>Collection</strong> as a table.</blockquote><p>5. To visualize the sample documents, we can choose in the UI a specific Collection, like <em>airline</em> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBzm0Oo1QROfzEkLvyIJZQ.png" /></figure><p>6. We can import some data by using the tool <a href="https://docs.couchbase.com/server/current/tools/cbimport-json.html"><strong>cbimport</strong></a>, or load it directly through the browser. Additionally, there are sample buckets available that we can use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xiRBrUR8scjsd7G9yvKPg.png" /></figure><p>Now that our bucket is ready, the next step is to configure access to the cluster. 🎯</p><h4>Cluster Access Configuration</h4><p>To allow the AWS lambdas to connect to our Couchbase Capella cluster, we need to configure two key settings: <strong>whitelisting the IP address</strong> from which the connection will be made and <strong>creating the necessary database credentials</strong>. All of these steps will be performed on the <strong>Connect</strong> and <strong>Settings</strong> Tabs.</p><blockquote>This ensures secure and authorized access between Lambda and Couchbase Capella.</blockquote><ol><li>On the Connect tab, click on Allowed Io Addresses, mentioned in step <em>1. Add an allowed IP address to connect :</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nYwdxKZgLsOYfh_fPt6OA.png" /></figure><p>2. In the <strong>Settings</strong> tab, you’ll need to specify which IP addresses can access your Couchbase Capella cluster. You have two options: either add your <strong>current IP address</strong> to restrict access to your machine or <strong>allow all addresses</strong> by entering 0.0.0.0/0. While the second option is not recommended for production due to security risks, it’s convenient for testing purposes. For this tutorial, I’ll select <strong>Allow All</strong>, confirm the change, and proceed with the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*LW-6Yun-fBSZi4igsi9CXQ.png" /></figure><p>3. Click on Add Allowed IP</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*yYjyq2uPMHckmlqy3QH4ig.png" /></figure><p>4. On the same tab <strong>Security</strong>, create a<strong> Cluster Access</strong> user, which will serve as the credentials for connecting our AWS lambda application to <strong>Couchbase</strong> <strong>Capella</strong>. In a production environment, it’s crucial to follow the <strong><em>Least Privilege Principle (LPP)</em></strong> by granting only the necessary permissions to minimize security risks. However, for this test, I’ll create a user with <strong>read/write access to all scopes in all buckets</strong> to simplify the setup :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*KTe8DRitDfg4-uMRMzOWkA.png" /></figure><p>Optionally, you can proceed to <strong>Steps 4 and 5</strong> if you want to explore <strong>code snippets</strong> and see how to establish a connection to Couchbase Capella using your preferred programming language. These steps provide detailed guidance on integrating the database with your application, making it easier to get started with development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCbgcyFWRjHBg_wFqoKxIg.png" /></figure><p>And that’s it! Our Couchbase Capella cluster is now fully configured and ready to be accessed by AWS Lambda 🙌. We’re all set to start making requests and building the serverless application.👍</p><h4>Step 2: Deploying the API Serverless Application Using AWS SAM</h4><p>Our application will consist of 4<strong> main Lambda functions</strong> (CRUD operations) with an additional <strong>bonus Lambda</strong> to handle search by Airline name. Each Lambda function will be <strong>isolated</strong> and dedicated to a specific task to maintain a clear separation of concerns.</p><p>Those lambdas will be exposed via <strong>API Gateway</strong>, which will route incoming requests to the appropriate Lambda function based on the API endpoint. Finally, the chosen language is <strong>Node.js</strong> taking advantage of its event-driven, non-blocking I/O model, which is ideal for serverless applications.</p><p>For deployment, we’ll be using <strong>AWS SAM (Serverless Application Model)</strong>, which provides a smooth and streamlined way to define, test, and deploy serverless applications.</p><p>One of the key benefits of SAM is its ability to <strong>run the full API locally</strong> for testing, allowing us to simulate the entire environment before deploying to the cloud. Once we’re ready, we can deploy the application with a simple <strong>CLI command.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*osTbqw2QjnDdb5gc.png" /></figure><ol><li>To get started, we can clone the repository using the following command, this repository contains all the code of our API.</li></ol><pre>$&gt; git clone https://github.com/hatim-heffoudhi/couchbase-aws-sam-lambda-sample.git<br>$&gt; cd couchbase-aws-sam-lambda-sample</pre><p>2. Install all necessary dependencies required for the project:</p><pre>$&gt; npm install</pre><p>3. Open the file <strong>template.yaml</strong>, In the <strong>Global section</strong>, you’ll find placeholders for the Couchbase environment variables. Update them with the following values from your Couchbase Capella configuration:</p><ul><li><strong>COUCHBASE_HOST</strong>: Enter the <strong>host URL</strong> from the <strong>Connect tab</strong> of your Couchbase Capella dashboard (this will typically look something like cb.xxxxx.cloud.couchbase.com).</li><li><strong>COUCHBASE_BUCKET</strong>: Set this to the <strong>bucket name</strong> you want to use, in this case, travel-sample</li><li><strong>COUCHBASE_USERNAME</strong>: Provide the <strong>username</strong> you created for accessing the cluster (this is the one you set up when creating the cluster access user).</li><li><strong>COUCHBASE_PASSWORD</strong>: Enter the <strong>password</strong> associated with the access cluster user.</li></ul><p>Example :</p><pre>Globals:<br>  Function:<br>    LoggingConfig:<br>      LogFormat: JSON<br>    Environment:<br>      Variables:<br>        COUCHBASE_HOST: &quot;cb.26engrxo9s19emrz.cloud.couchbase.com&quot;<br>        COUCHBASE_BUCKET: &quot;travel-sample&quot;<br>        COUCHBASE_USERNAME: &quot;lambda-sample-user&quot;<br>        COUCHBASE_PASSWORD: &quot;&lt;Password&gt;&quot;</pre><p>4. Build the API, <em>this operation will download packages, compile the API, copy sources…</em></p><pre>$&gt; npm run build</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbrXVMdZVrPSk1X1Ssti4g.png" /><figcaption>Result npm run build:api</figcaption></figure><p>After a few seconds, the build will finish and reach a “succeeded” state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3eeLPHIHl2UpBOFIpFaYg.png" /></figure><p>5. Once the API is built, we can run it locally on our machines. This command will start 5 Docker containers, with each one dedicated to a specific Lambda function.</p><pre>$&gt; npm run start:api</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64XuKaePQ3pp810NJYoeng.png" /><figcaption>result mention docker containers started with aws sam</figcaption></figure><p>6. In the cloned repository, import the <a href="https://github.com/hatim-heffoudhi/couchbase-aws-sam-lambda-sample/blob/main/postman_collection/sam-lambda-with-Capella.postman_collection.json">Postman Collection</a>, which includes all the preconfigured API calls for each of the Lambdas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*-g3go0U2fb6s7zsvOFdUVg.png" /></figure><p>Let’s test the “Get All Airlines” endpoint. Initially, you’ll notice the response time is 12.18 seconds. This is due to the cold start of the local Lambda on your machine, and it may vary depending on your machine’s configuration.</p><p>The code of the lambda will use the query service with a key Set pagination, specifying a limit and the lastKey for the next page…</p><pre>// key Set pagination<br>const query = `SELECT META().id, *<br>               FROM \`airline\`<br>               WHERE META().id &gt; $lastKey<br>               ORDER BY META().id LIMIT $limit`;<br>const options = {parameters: {lastKey, limit}};<br><br>// Execute query within the specified scope<br>const result = await scope.query(query, options);</pre><p>On PostMan, Run the following HTTP URL, this will trigger the lambda &quot;Get All Airlines&quot; to use the query service, following the limit and the lastKey and return the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-comr5xaSuGji6mMOIQ5Tw.png" /></figure><p>All Lambdas use the singleton pattern for the Couchbase connection (managed outside the handler). This helps speed up access and ensures a good connection pool is maintained. As a result, after the second call, the response time is reduced to 510ms (<em>This time will be reduced by following best practices, such as optimizing the network, reducing hops, and configuring the machine and cluster efficiently).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzgrfOtBR_0GS7DvcZZHlQ.png" /></figure><p>This next image shows the result of the lambda which returns a specific airline by Id :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cNlNk37xNcqaNggjaLgRg.png" /></figure><p>That it! congratulations, you have now run it locally your serverless stack using AWS lambda with the fully managed database Couchbase Capella.</p><h3>How To Deploy it to your AWS account?</h3><p>Thanks to SAM, our little friend, deploying our stack is a breeze — just one command and we’re good to go!</p><pre>$&gt; sam deploy --guided</pre><p>In the guided mode, we have more choices to make, like choosing the region, and name, disabling rollback…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMCjK1wRa9VpogZlnVlVFA.png" /></figure><p>After a few seconds, SAM will check all the selected elements and deploy them to our AWS account, creating all the necessary resources like roles, functions, and API Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4e0x4pM_7ZdNNXxGVM2fQ.png" /></figure><p>Once the deployment is complete, the Outputs will show us the API Gateway URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-oqsbicl_UYi9OcS1Tlcw.png" /></figure><p>If we access to our AWS account, we can see the API and the lambdas are deployed automatically with SAM :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g91C8sPd0F1jGsv0qbWLLA.png" /><figcaption>Deployed API Gateway</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYl5VLZLPMMl7TEmmg5-Pg.png" /><figcaption>Deployed AWS Lambdas</figcaption></figure><p>Now It&#39;s deployed, let&#39;s make a test to get all airlines, by copying the URL of the API Gateway, we notice with the actual configuration, the time is around 67ms, <em>This time can be drastically reduced with a good configuration, including networking optimizations (like VPC Peering) and proper cluster configuration. We will talk about that in the next Article adding automation provisioning with the Hashicorp Terraform Provider for Capella👌</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdKMWA4R5vcyxJ3b8Eqf5g.png" /></figure><p>If you need to clean and delete the deployed resources, it&#39;s just by one command :</p><pre>$&gt; sam delete --stack-name sam-lambda-with-Capella</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgF5ruyJoGHxYE0RUoo3Zw.png" /></figure><h3>BONUS - ( Lambda using FTS/Search Couchbase)</h3><p>As per the documentation :</p><p>The <em>Search</em> Service provides extensive capabilities for search engine-like querying. These capabilities include, but are not limited to:</p><ul><li><em>Language-aware</em> searching; allowing users to search for, say, the word beauties, and additionally obtain results for beauty and beautiful.</li><li><em>Scoring</em> of results, according to relevancy; allowing users to obtain result-sets that only contain documents awarded the highest scores. This keeps result-sets manageably small, even when the total number of documents returned is extremely large.</li><li><em>Fast indexes</em>, which support a wide range of possible text-searches.</li><li><em>Geospatial</em> queries, to return documents that contain a specified geographic location.</li><li><em>Range</em> searches, including numeric range and date range queries.</li><li><em>Fuzzy</em> matches, <em>regular expression</em> searches, and <em>wildcard</em> searches.</li></ul><p>Let’s create a new Search Index by clicking on “Search” and then selecting “Create Search Index.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHW9VXRusibw_kWi3nRi8A.png" /></figure><p>Since our API is dedicated to managing airlines, we will choose the “Airline” collection and opt to index it by selecting the field mapping, as shown in the next image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGSL5urTF4MEJHKRnSJXXw.png" /></figure><p>The created index will index the name field as text</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXnYGC0-3ghv8DdgzXCj_w.png" /></figure><p>The code of the lambda :</p><pre><br>        const ftsResult = await scope.search(<br>            &#39;airlines-name-index&#39;,<br>            couchbase.SearchQuery.match(name).fuzziness(2),<br>            {limit: limit}<br>        );<br>        console.log(&#39;RESULT:&#39;, ftsResult)</pre><p>Let’s test the API now by searching for “American Air.” This will return all airlines whose names contain “American” and/or “Air”(both). That’s why we may see some documents, like “Rainbow Air,” being returned as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWkKrzILTxI0AXZ-O3uMvA.png" /></figure><p>Now let&#39;s test the fuzziness, which allows for approximate matches, handling slight misspellings or variations in the search term.</p><p>While searching for &quot;AmeriTXN&quot;, it may be a typo in the search, but the result contains &quot;Amercian&quot;. 👍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJBJlK78Z1ybLQLe91bTLQ.png" /></figure><p>Enjoyed? Clap 👏, share, and follow for more!</p><p><a href="https://github.com/hatim-heffoudhi">Github link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1059910ec2f0" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/building-a-serverless-application-with-aws-lambda-and-couchbase-1059910ec2f0">Building a Serverless Application with AWS Lambda and Couchbase</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Can I minimize my AWS Bills $$ based on…]]></title>
            <link>https://awstip.com/how-can-i-minimize-my-aws-bills-based-on-ba64ff3cb9d4?source=rss-74ac865be93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba64ff3cb9d4</guid>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[dollar]]></category>
            <category><![CDATA[sdk]]></category>
            <dc:creator><![CDATA[HATIM HEFFOUDHI]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 19:17:30 GMT</pubDate>
            <atom:updated>2025-03-10T11:19:07.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qFwcOiT8B_s85GWV" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is always fulfilling to migrate or switch to the cloud, we gain in performance, resiliency and high availability, Not to mention the ease of launching and migrating our applications has become child’s play.</p><p>But with great power comes great responsibility, we must adopt a new mindset of cost monitoring, especially since the billing model depends on the service, either by request or by the number of running hours… THE FINOPS aspect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*fWp7I_g32Xpr5HcekwxW-Q.png" /><figcaption>imfflip.com</figcaption></figure><p>Sometimes either in testing or in production environments, there are always improvements available to reduce cost like changing instance type, Stopping Instances during no working hours….</p><p>In this article, I will give you my personal tips that I have used. I won’t talk about the Reserved Instance part or spot instances, It’s a good way to minimize the cost up to 72% but I’m focusing right now on On-demand workload.</p><h3>If My Workload is on EC2</h3><p>It happens to all of us to forget to turn off our EC2 machines, Or to remember at midnight like that right? :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*xNyERieceDXKeIZw-G1Xvg.jpeg" /><figcaption><a href="https://i.imgur.com/TLZQDUX.jpg">https://i.imgur.com/TLZQDUX.jpg</a></figcaption></figure><p>Or if you have a fleet of EC2 instances, And you want to stop them in no-working hours and weekends.</p><p>So let’s begin with some tips. 🐱‍🏍</p><h4>AWS Systems Manager</h4><p>With the SSM automation service, preconfigured documents are available for starting and stopping machines with the Ids of the instances as input.</p><p>You can schedule it with EventBridge, a custom pipeline, or run them manually.</p><p>Our 🌟 documents :</p><ul><li><strong>AWS-StartEC2Instance</strong>: contains steps to change the state of the instance to a running state</li><li><strong>AWS-StopEC2Instance</strong>: contains steps to change by forcing the instance state change to a stopped state</li></ul><p>🚩At the moment of writing this article, It&#39;s working only with Instance Id and not Tags. I hope AWS will change this to enable Tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PT0Fff4wsN5CiABUm0aWAw.png" /><figcaption>SSM/Automation</figcaption></figure><h4>AWS CLI</h4><p>For CLI lovers, and shell scripting 🤩 There are your three infinity stones :</p><ul><li><strong>aws ec2 start-instances</strong></li><li><strong>aws ec2 stop-instances</strong></li><li><strong>aws ec2 describe-instances \ — filters ‘Name=tag:’${TAG}’,Values=*’</strong></li></ul><p>Those commands, we can combine them to start or stop instances based on a Tag, you can automate this script within a pipeline or with Run Command, or manually :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88fcdd21b053c5b802e33ed0e0716e63/href">https://medium.com/media/88fcdd21b053c5b802e33ed0e0716e63/href</a></iframe><h4>AWS SDK</h4><p>For SDK Lovers 🐬, on node js, python or Java… we can change the instance states with the SDK based on our needs, for example, this snippet code present the same logic by getting the instances Id with Tag and starting them :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aafcb43635a76655652d2461761a904f/href">https://medium.com/media/aafcb43635a76655652d2461761a904f/href</a></iframe><p>The same treatment to stop machines EC2 with AWS SDK :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/424acbea589ba96eb06647813f786879/href">https://medium.com/media/424acbea589ba96eb06647813f786879/href</a></iframe><p>We can run this treatment on AWS lambda triggered from an API Gateway or a CloudWatch Event Rule. For example, in this Sam Template we trigger the stop machines lambda with EventBridge Cron expression :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40749c5b261cebd0cfc1169132af29cc/href">https://medium.com/media/40749c5b261cebd0cfc1169132af29cc/href</a></iframe><h4>Instance Scheduler</h4><p>The Scheduler instance is deployed as aCloudFormation stack in 5 min which will create DynamoDB, Lambda, SNS…This Solution helps you control your AWS resource cost by configuring start and stop schedules for your Amazon Elastic Compute Cloud (Amazon EC2) and Amazon Relational Database Service (Amazon RDS) instances.</p><p>After deployment, you configure the business time period to automatically stop instances outside of business hours every day</p><p><a href="https://aws.amazon.com/solutions/implementations/instance-scheduler/">https://aws.amazon.com/solutions/implementations/instance-scheduler/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uHL1lE4Z8G_1bTJG.png" /><figcaption><a href="https://aws.amazon.com/solutions/implementations/instance-scheduler/">https://aws.amazon.com/solutions/implementations/instance-scheduler/</a></figcaption></figure><h3>If My Workload is on EKS</h3><p>If you have an EKS ☸️ , The instance scheduler is not the best option to use, because, at the moment of writing this article, they do not have automation for the autoscaling groups.</p><p>For the EKS you can reduce the capacity of the autoscaling group in the evening and put it back in the morning for example.</p><h4>AWS CLI</h4><p>With the CLI, we can change the desired capacity like this example :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d42ec9b1bbd9b0c8d1a55bb5d4b1fe40/href">https://medium.com/media/d42ec9b1bbd9b0c8d1a55bb5d4b1fe40/href</a></iframe><h4>AWS SDK</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9519440871acabe7fdfc3f842f067f12/href">https://medium.com/media/9519440871acabe7fdfc3f842f067f12/href</a></iframe><h4>Cluster Autoscaler</h4><p>Another tool to use is the Cluster Autoscaler, it deployed inside your cluster 👇</p><p><a href="https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/cloudprovider/aws/README.md">autoscaler/cluster-autoscaler/cloudprovider/aws/README.md at master · kubernetes/autoscaler</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba64ff3cb9d4" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/how-can-i-minimize-my-aws-bills-based-on-ba64ff3cb9d4">How Can I minimize my AWS Bills $$ based on…</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construire un microservice serverless & le déployer sur AWS (part 3)]]></title>
            <link>https://medium.com/@hatim.heff/construire-un-microservice-serverless-le-d%C3%A9ployer-sur-aws-part-3-dca93c9e0ccb?source=rss-74ac865be93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dca93c9e0ccb</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[HATIM HEFFOUDHI]]></dc:creator>
            <pubDate>Wed, 03 Nov 2021 10:55:15 GMT</pubDate>
            <atom:updated>2021-11-03T10:55:15.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92pEZlnVh8NPRgzMyC6LJQ.png" /></figure><p>Bienvenue dans cette troisième et dernière partie de notre saga “Construire un microservice serverless &amp; le déployer sur AWS”. Durant les deux premiers articles, nous avons vu comment concevoir et développer notre microservice Serverless. Pour ceux qui n’ont pas eu encore eu le temps de les voir, je vous invites à lire 👉 <a href="https://www.linkedin.com/feed/update/urn:li:ugcPost:6774665537743028224?updateEntityUrn=urn%3Ali%3Afs_feedUpdate%3A%28*%2Curn%3Ali%3AugcPost%3A6774665537743028224%29">partie 1</a> et <a href="https://www.linkedin.com/feed/update/urn:li:ugcPost:6797540549541797888?updateEntityUrn=urn%3Ali%3Afs_feedUpdate%3A%28*%2Curn%3Ali%3AugcPost%3A6797540549541797888%29">partie 2</a>.</p><p>Dans cet article, nous allons explorer les différents Stratégies et outils pour le déployer.</p><p>En introduction je vous propose un tour de table pour présenter les différents services utilisés.</p><h3>La suite CICD AWS:</h3><p>La suite CICD offre des services entièrement gérés par AWS qui nous déchargent de toutes les opérations de gestion, maintenance opérationnels et de nous focaliser sur notre SDLC(Software Development Life Cycle), qui sont :</p><ul><li>CodeCommit est un service de dépôt de code source sécurisé et extrêmement évolutif qui héberge les référentiels Git privés. Concernant l’aspect sécurité on peut affiner les accès vers les branches et opérations via des des rôles IAM. Les opérations git peuvent s’effectuer en SSH, HTTPS ou en HTTPS GRC. On peut aussi notifier, créer des “Pull Request” et désigner un pool de membres pour les approuver ou les refuser.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*LkkLAv3x6moMwanR" /></figure><ul><li>CodeBuild est un service de build permettant d’effectuer des compilations de code source suivant le runtime cible, lancement et reporting des tests, génération et packaging des artifacts, en se basant sur un fichier de spécification de build nommé buildspec.yml. Avec ce service, On peut associer des variables d’environnement récupérés via SSM Parameter Store ou Secrets Manager Service pour protéger les valeurs sensibles tel que des API KEY ou mot de passe…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*6qEcIUWQaJcLaa4W" /></figure><ul><li>CodeDeploy est un service qui permet d’automatiser les déploiements des applications vers différentes plateformes tel que du EC2, machines “on Premise”, Serverless et container comme AWS Lambda et ECS. Le service offre différentes stratégies de déploiement ( In place, Blue Green, Canary…) qu’on verra en détails par la suite</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*hziROlcq3S61kaR_" /></figure><ul><li>CodePipeline est un service d’intégration et livraison continue, il permet d’orchestrer l’automatisation du process de livraison ( CI/CD) en partant à partir d’une Feature déployé dans un code source, compilé, testé et déployé vers des plateformes cibles et vers différents environnements. CodePipeline propose des intégrations avec de multiples services et outils tel que Jenkins, CloudFormation, CodeDeploy, ElasticBeanstalk….</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*_1nnhALjtNUi8t8Y" /></figure><h3>Stratégies de déploiements</h3><p>Parfait, à présent parlons des différentes stratégies de déploiements proposées par CodeDeploy pour notre application, connue sous l’intitulé Preference type d’une configuration lambda :</p><ul><li>All-at-once : Ce type de déploiement déplace immédiatement tout le trafic vers la nouvelle version mise à jour de la Lambda.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*7nZKZMU60QkMaRP0" /></figure><ul><li>Canary : Ce type de déploiement déplace un pourcentage du trafic dans le premier incrément vers la nouvelle version. Le pourcentage restant est déployé après un temps configuré, exemple Canary10Percent5Minutes, déplace 10% du trafic dans le premier incrément. Les 90 % restants sont déployés 5 minutes plus tard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*JtluM1Pj5usFbUMV" /></figure><ul><li>Linear : Ce type de déploiement déplace un pourcentage du trafic vers la nouvelle version déployée toutes les x minutes ou via une période configurée. Exemple Linear10PercentEvery1Minute, déplace 10% du trafic toutes les minutes jusqu’à ce que l’intégralité du trafic soit déplacée :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vvbygKiqvvblP8gu" /></figure><h3>Rollback en cas de probléme</h3><p>“Everything fails all the time” la fameuse citation de Werner Vogels CTO AWS, présente la réalité des choses, chaque système finira à un moment d’échouer, la question est comment prévenir ce genre de panne et y remédier rapidement.</p><p>Avec le service CodeDeploy, on peut anticiper et prévenir des problèmes qui peuvent réagir lors du déploiement d’une nouvelle version. En associant un rollback avec des alarmes tel que des erreurs 500 issues de la nouvelle version déployée, On peut revenir facilement et de façon automatique à l’ancienne version, si ces alarmes ont été déclenchées dans la phase de test de la version à déployer et sans impacter le système.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*R7B8SeJp7EiUdkyo" /></figure><h3>Déploiement de l’application</h3><p>Notre pipeline de déploiement avec CodePipeline se composera de trois stages :</p><ul><li>Stage 1 : Récupération du code source suite à un push à partir du CodeCommit</li><li>Stage 2 : Build du code source et génération des artifacts à l’aide de CodeBuild</li><li>Stage 3 : Déploiement dans un environnement via CloudFormation + CodeDeploy</li></ul><p>On dispose déjà du CodeCommit, il nous reste une configuration à effectuer pour CodeBuild et CodeDeploy.</p><h3>Buildspec.yaml</h3><p>Le build sera effectué via CodeBuild qui nécessite un fichier yaml appelé buildspec.yml</p><p>Ce fichier est nécessaire car il contient l’environnement d’exécution, les commandes à effectuer ainsi que le packaging des artifacts générés :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M11W2VQMTBiAY0-Z" /></figure><ol><li>On spécifie nodejs comme environnement d’exécution (runtime) pour compiler et tester notre application js.</li><li>On spécifie dans cette section les commandes à lancer dans notre build, qui commence par installer les dépendances et pour finir packager le template SAM avec la commande sam package.</li><li>Dans cette section, on indique au CodeBuild l’emplacement des artefacts à récupérer et à les compresser sous format zip pour être fournies pour les prochaines étapes de notre build.</li></ol><p>Dans ce fichier buildspec, on remarque qu’il y a 2 phases configurés “install” et “build”, mais en réalité, il existe plus de phases exécutés, l’enchainement suivant montre le passage des étapes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*6N6KyQiUWoqBnef2" /></figure><blockquote><em>La phase UPLOAD_ARTIFACTS s’effectue toujours, même si la phase BUILD phase échoue.</em></blockquote><p>Pour notre build, dans la console on peut les voir dans la partie “Phase details” :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/0*0zc88VUnG65l66ag" /></figure><h3>Configuration CodeDeploy</h3><p>Maintenant il faut qu’on configure notre déploiement avec CodeDeploy.</p><p>Avec notre template SAM, on s’est décharge de la création d’une application et une configuration de déploiement via CodeDeploy, il suffit juste de rajouter les trois lignes suivantes qui vont faire le nécessaire :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vX5RCzneri5-H6K7" /></figure><ol><li>Cette propriété indique d’incrémenter la version de la lambda lors d’un déploiement en en la pointant vers l’alias live</li><li>Cette propriété indique au CloudFormation de créer une application CodeDeploy de type Lambda, le rôle IAM ainsi qu’un Deployment Group. A noter que CloudFormation générera des noms pour chaque composant avec de nouveaux ID.</li><li>Cette propriété indique qu’on prévoit d’utiliser la stratégie Linéaire avec 10% d’incrémentation vers la nouvelle version chaque à 1min, au total on arrivera à 100% vers la nouvelle version en 10 min, ça nous donne l’opportunité de bien tester la nouvelle version et de procéder à un rollback en cas de problème.</li></ol><h3>Lancement du déploiement</h3><p>Notre déploiement a été lancé avec un Deployment type Blue/Green vers la plateforme AWS Lambda :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*Sy1r8ZR2y-3pjWhB" /></figure><p>Dans la partie Traffic shifting process on remarque que le déploiement va incrémenter la nouvelle version “Replacement” de 10% chaque minute, ci-dessous une vue après 2 min passé :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*bkewyLSuhU8sb635" /></figure><p>Au niveau des Alias de notre application, on remarque que l’alias live pointe vers deux versions 4 et 6 en respectant le pourcentage de trafic alloué à chaque version. C’est normale car pour ce type de déploiement, les deux versions 4 et 6 reçoivent une portion configuré du trafic :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*dJtdd_Dusqg9TONK" /></figure><p>Après 10 min, le déploiement s’achève :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*rlBkzgDPTb-8W5km" /></figure><p>On remarque que le trafic est maintenant à 100% vers la nouvelle version (Replacement)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*W9dF64E6O-Nk1LcQ" /></figure><p>En vérifiant la version associée à l’alias live, on remarque qu’elle est sur 100% sur la v6 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*u_H9qpPNjbleSrCL" /></figure><h3>Les Change Set de CloudFormation</h3><p>Tout changement ou déploiement a un impact sur l’architecture, pour bien surveiller , il est recommander de travailler avec les “change set”, qui nous présentent les différents changement à réaliser sur une Stack CloudFormation.</p><p>On exécute le change set qui contient les changements suivants, les actions avec l’indicateur de remplacement, c’est un indicateur pour être informé qu’un composant sera remplacé ou pas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*2kJ300Rnpd5SHqIO" /></figure><p>En cliquant sur l’onglet Changes, on peut voir les actions et changements à effectuer dans notre change set :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*PfXeJaqPwxmSCCqV" /></figure><p>📢 C’est le moment idéal de vérifier si un déploiement d’un composant posséde la valeur Replacement à True. Car pour des composants avec de tel valeur, on peut perdre les données tel que des composants RDS ou autre. Pour y remédier, il suffit dans ce cas de mettre les bonnes valeurs de UpdatePolicy et DeletionPolicy afin de prendre un Snapshot en cas de remplacement.</p><p>L’action “execute-change-set” exécute le change en coordination avec CodeDeploy suivant la stratégie paramétré.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QSuOWQYI5Jy2b214" /></figure><p>Au finale, le rendu de notre pipeline sera comme suit, avec les trois stages précédemment cités en partant par la récupération du code source de CodeCommit, build avec CodeBuild et déploiement avec CloudFormation + CodeDeploy :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/0*mUZQsdtMcpTR2iv2" /></figure><p>A présent on pourra tester notre application à partir d’une API Gateway généré :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8V30V86yMjEmQp9d" /></figure><p>Faisons un test avec l’url fournie qui est sous la forme de :</p><p>👉 <a href="https://${idapigateway}.execute-api.${region}.amazonaws.com/$%7Bstage%7D">https://${idApiGateway}.execute-api.${region}.amazonaws.com/${stage}</a></p><ul><li>${idApiGateway} = L’id généré pour notre API Gateway</li><li>${region} = Région de déploiement</li><li>${stage} = stage de l’API Gateway</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*DuPREBdOtck0JwS9" /></figure><p>L’appel vers l’API Gateway déployé est transféré vers la Lambda “create-user-function” qui est invoqué en créant un nouveau user dans notre table DynamoDB.</p><p>On procède à un autre test, en appelant la lambda “get-all-users-function” via l’url de l’API Gateway pour tester la récupération des utilisateurs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*-BC8qRlHiSxHzUHL" /></figure><p>👍👍 This is it ! Nous avons déployé notre application depuis notre CodeCommit en passant par CodeBuild et CodeDeploy + CloudFormation.</p><h3>👌 My Take away :</h3><ul><li>CodeDeploy n’est à ce jour de l’écriture de l’article pas intégré avec EKS, par contre il existe des moyens pour lancer des déploiement Helm ou autre CLI vers EKS dans un CodePipeline.</li><li>Privilégiez la stratégie de déploiement qui vous convient le mieux, que ça soit in place ou Blue/Green, Canary suivant l’environnement cible, car chaque stratégie à des avantages et inconvénients basés sur ( Temps déploiement, Temps de Rollback, Coût, Changement DNS…)</li><li>Isoler les environnements par Stack, avoir une stack dev, une stack staging et une prod, ou suivant les environnements que vous avez, Je recommande cette méthode car elle permet d’isoler les ressources dédiées à chaque environnement et de ne pas les mélanger.</li><li>Associer des Rollback avec des alarmes issues des vérificateurs de déploiements. Sur un déploiement Lambda, on peut configurer des testeurs sous forme de hook, qui testent la nouvelle version déployé avant qu’elle soit visible, et de déclencher l’alarme en question pour procéder à un Rollback en cas de problème.</li></ul><h3>Bonus — AWS Chabot</h3><p>L’article n’est pas encore finit, je vous mets ici un petit bonus, où on peut faire du ChatOps en utilisant le service Chatbot AWS.</p><p>Dans notre exemple, on a configuré le bot AWS pour nous prévenir des déploiements, pouvoir vérifier et lancer les commandes à partir de Slack.</p><p>Exemple d’une notification lorsqu’un déploiement se lance :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*36CKZpYRMR7JkTmO" /></figure><p>Le Bot nous notifie aussi des Status de chaque stage (Source, Build, Deploy)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*IWo7M5X8z28w7Nsi" /></figure><p>On peut lui demander de nous fournir le statut de notre changement CloudFormation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*98605sy-JidlciZO" /></figure><p>Et pourquoi pas, lancer un test de la Lambda déployé pour confirmer le fonctionnement de la nouvelle version :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*XdBOW06H-lc1L-q3" /></figure><p>Voila la fin de cette SAGA, qui a regroupé la maniéré de concevoir, développer et déployer notre microservice Serverless. Merci à vous !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dca93c9e0ccb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construire un microservice serverless & le déployer sur AWS (part 2)]]></title>
            <link>https://medium.com/@hatim.heff/construire-un-microservice-serverless-le-d%C3%A9ployer-sur-aws-part-2-90913966f7c5?source=rss-74ac865be93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/90913966f7c5</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[HATIM HEFFOUDHI]]></dc:creator>
            <pubDate>Wed, 03 Nov 2021 10:48:21 GMT</pubDate>
            <atom:updated>2021-11-03T10:48:21.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*uEcH-SzgbO8WyAECXdVjUQ.png" /></figure><p>Bienvenue dans la deuxième partie de la série “Construire un microservice serverless &amp; le déployer sur AWS”. Dans la partie 1, nous avons parcouru les notions du monolithe, des architectures microservices, les services AWS de notre microservice et les étapes d’installation du Workspace, pour revoir cette partie 👉 <a href="https://www.linkedin.com/pulse/construire-un-microservice-serverless-le-d%C3%A9ployer-sur-hatim-heffoudhi/">Partie 1</a></p><p>Dans cette partie, nous allons parcourir la structure de notre microservice qui est basée sur une architecture Serverless développé en Node.js ⚡.</p><h3>Structure Projet</h3><p>La structure du projet est composée de 4 couches (Layers), inspiré du modèle DDD (Domain Driven Design — Conception piloté par le domaine) 👌 où notre domaine star est le domaine user 🙎‍♂️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*eE4A5fNrl6xYTtlZ" /></figure><p>Chaque couche a un objectif précis 🎯, on a :</p><ul><li>Couche application : (i.e. “application service layer”) point d’entrée du microservice. Elle fournit à l’utilisateur les opérations du microservice (aussi vue comme la couche C du modèle MVC) ne contient pas de logique métier et joue l’interface entre la couche utilisateur et la couche domaine. Dans notre cas elle fournit 3 points d’entrée HTTP aux différents lambdas.</li><li>Couche domain : (i.e. “domain layer”) contient le noyau du microservice. Toutes les informations et comportements du domaine sont mis dans cette couche. Par exemple les règles métiers implémentés ou encore les contrats d’interface de persistance qui seront implémentés dans la couche infrastructure…Cette couche est le relais entre la couche application et la couche infrastructure.</li><li>Couche infrastructure : (i.e. “infrastructure layer”) permet d’implémenter les repositories du domaine (aussi vue comme la couche de persistance de données). Au niveau de cette couche, les domaines sont transformés en entités et enregistrés dans un dépôt de données (Base de donnée, Fichier, File de message…). Dans notre exemple, il s’agira de DynamoDB, mais on peut parfaitement rajouter une autre infrastructure comme AWS RDS ou AWS Document DB…</li><li>Couche zconfig : (optionnelle) Même si elle ne fait pas partie du modèle DDD, j’ai choisi de la faire apparaitre pour indiquer que c’est une couche à implémenter aussi. Elle nous permettra de regrouper tous nos fichiers de configuration nécessaire au projet, par exemple la configuration du conteneur IoC en utilisant le framework <a href="https://github.com/inversify/InversifyJS">Inversify.js</a> ✨</li></ul><p>Dans notre microservice, vous allez remarquer qu’il y a des décorateurs/annotations au niveau des classes de nos lambdas pour respecter les principes OO, SOLID, DRY, IOC… Par exemple avec Java spring boot, il y a les annotations (@Service,@Repository…). J’ai essayé de suivre la même logique en mettant en place ces décorateurs avec le framework inversify-js 🤩.</p><p>On va à présent parcourir le microservice, décortiquer le code et comprendre les différentes couches et interactions ( allons-y 😎)</p><h3>Le Handler</h3><p>🚪 Toute fonction lambda est définie par un point d’entrée appelé handler. Ci-dessous le handler de la fonction “user-create-function” :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Cs2xdSdwsdLwzHl" /></figure><ol><li>Nous commençons par initier le userService en le récupérant du container IoC. On remarquera qu’il est déclaré à l’extérieur du handler. L’objectif est qu’il ne soit pas initialisé à chaque invocation et qu’il soit disponible pour les futurs appels. Cette approche est préconisée pour rendre disponible un service pour toutes les futures invocations mais aussi pour des gains en mémoire et rapidité.</li><li>Nous déclarons le point d’entrée (NDLR : Le handler) avec comme paramètre un event d’un appel API Gateway. Il existe de nombreux types d’events pour déclencher les lambdas, comme les events S3, SNS, SQS, CloudWatch Event…. En réponse de notre event, le retour est de type API Gateway Proxy Result.</li><li>Nous transformons le body de la requête en domaine, on peut aussi parfaitement utiliser des mapper.</li><li>Nous appelons la méthode saveUser du service “userService”. Cette méthode contient le traitement d’enregistrement de l’utilisateur. Elle prend en paramètre le domaine user ainsi qu’en sortie.</li><li>Nous retournons la réponse si succès, code 200 👍.</li><li>En cas d’erreur, nous retournons le message avec le code 500.</li></ol><h3>La class Service🛒</h3><p>La classe UserService reçoit la commande de création du domaine en le sauvegardant dans la base à l’aide du userRepository.📼</p><p>Cette classe est annotée par le décorateur @service afin qu’elle soit instanciée et injectée dans notre conteneur IoC. Elle injecte le userRepository récupéré du conteneur IoC, comme indiqué dans le constructeur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dw3CLtIJDdKhLzRb" /></figure><h3>La class Repository📹</h3><p>La classe UserRepository qui fait partie de la couche infrastructure, contient les opérations DynamoDB et se décompose comme ceci :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f3HgDsCKL4oPnC6T" /></figure><ol><li>Nous déclarons notre client dynamoDBClient avec comme type DocumentClient. Cette dernière contient toutes les opérations de CRUD DynamoDB.</li><li>La variable PREFIX, sert à donner des informations concernant nos enregistrements dans la table DynamoDB. Elle est un préfixe pour notre Hash Key/Sort Key, afin qu’on puisse gérer d’autres domaines dans la même table. Cette approche nous simplifie le filtre des enregistrements en utilisant l’expression “<a href="https://docs.amazonaws.cn/en_us/amazondynamodb/latest/developerguide/Query.html#Query.KeyConditionExpressions">begins_with</a>” sur ce préfixe. On peut gérer aussi avec cette approche une base relationnelle dans une seule table DynamoDB (voir ce <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-modeling-nosql.html">lien</a>).</li><li>Nous récupérons la variable d’environnement TABLE_NAME, qui correspond à la table user. C’est une bonne pratique pour éviter de modifier le code pour chaque env(dev, staging, prod). Au niveau du déploiement, il faut juste pointer la variable vers le nom de la table de l’environnement cible (e.g dev-user-table, staging-user-table…).</li><li>Nous instancions le client DynamoDB, qui récupére les clés AWS à partir du profil AWS par défaut.</li><li>Cette partie a été rajoutée pour simplifier les tests aux équipes. Ils peuvent soit tester directement vers des tables DynamoDB du compte AWS ou tester les opérations en local. Pour cela, cette partie est activé via une variable d’environnement. Si elle est spécifiée avec la valeur “local”, alors le client pointera vers la table DynamoDB local dans le même réseau et inversement.💻</li></ol><p>Enregistrement d’un utilisateur :</p><p>Ci-dessous la composition de la méthode saveUser, utilisé pour enregistrer les utilisateurs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ljQCuyi0BY7OWf76" /></figure><ol><li>Nous utilisons un mapper pour transformer le domaine user en userEntity (Item DynamoDB).</li><li>Nous alimentons la clé primaire de l’item (Partition key, Sort key) avec les valeurs du préfix + un uuid généré.</li><li>Nous construisons les paramètres pour l’opération Put du DynamoDBClient. Ils se composent du nom de la table récupéré des variables d’environnement précédemment, et avec l’item construit dans l’étape N°1 et N°2.</li><li>Appel à la méthode PUT du client DynamoDB avec les paramètres de l’item à créer.</li><li>Nous utilisons à nouveau le mapper, pour transformer l’entité sauvegardé en domaine, pour le retourner à notre handler.</li></ol><p>On expose aussi d’autres opérations, comme la récupération d’un seul utilisateur, récupération de tous les utilisateurs. Ces opérations sont exposées via leurs lambdas et utilisent les méthodes de la classe UserRepository :</p><p>Récupération d’un utilisateur :</p><p>Ci-dessous la composition de la méthode findUserById</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X0dNkTDhb900R0dq" /></figure><ol><li>Construction des paramètres de la requête avec le nom de la table et la clé primaire de l’utilisateur. Le Sort key est alimenté avec la valeur INFO, pour cibler la ligne contenant les informations de l’utilisateur.</li><li>L’opération GET du client DynamoDB en lui passant les paramètres de l’étape N°1.</li><li>Nous utilisons le mapper pour transformer l’entité récupérée en domaine, pour la retourner au handler</li></ol><p>Récupération de tous les utilisateurs :</p><p>Ci-dessous la méthode pour récupérer tous les utilisateurs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PTVYVFj6R7XoFitS" /></figure><ol><li>Construction des paramètres pour cibler la table utilisateur récupéré des variables d’environnements.</li><li>La méthode utilisée pour cette action est la méthode scan. Elle permet de parcourir et renvoyer les enregistrements de notre table. Afin de récupérer toutes les données, on utilise une boucle basée sur la valeur du “LastEvaluatedKey”, qui nous indique la récupération du dernier enregistrement. Cette approche est recommandée pour éviter de récupérer qu’une partie des données. Avec ce champ on peut aussi implémenter une pagination.</li></ol><p>🎢Nous avons parcouru les différentes classes de notre microservice et l’interaction en couche, à présent passons à la description de notre microservice en ressource AWS</p><h3>SAM Template 📄</h3><p>Comme mentionné dans la <a href="https://www.linkedin.com/pulse/construire-un-microservice-serverless-le-d%C3%A9ployer-sur-hatim-heffoudhi/?lipi=urn%3Ali%3Apage%3Ad_flagship3_publishing_post_edit%3Bb64tcv1ESPmXq2CuCnbKvg%3D%3D">partie 1</a>, pour la description de notre stack AWS et son déploiement, nous allons utiliser l’outil SAM dont voici l’organisation du template :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VscLrM5QzhRE52l8" /></figure><p>1. Cette partie nous permet de définir les paramètres en entrée de notre template. On aura besoin de deux paramètres :</p><ul><li>LambdaNodeEnv, pour indiquer quel environnement choisir (local, dev, staging…)</li><li>TableName, pour indiquer le nom de la table DynamoDB.</li></ul><p>2. Cette section permet de définir une configuration globale telle que l’environnement Runtime, le point d’entrée (Handler) ou encore le timeout….Afin d’éviter de dupliquer la configuration et répondre au best practice DRY pour toutes les Lambdas déclarées dans le template.</p><p>Passons à présent à la section resources :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DlEfyBB2EUZmAF83" /></figure><p>3. La ressource API Gateway qui exposera nos fonctions. Nous avons paramétré le stageName avec le paramètre LambdaNodeEnv afin que pour chaque environnement, on a un stage dédié (dev/, staging/, prod/)</p><p>4. Cette section contient la déclaration de la ressource lambda CreateUser qu’on a parcouru tout à l’heure. Remarquez qu’elle ne contient pas beaucoup de configuration, car tout est a été renseigné dans la section Global (voir point N°2).👌</p><p>5. Cette section contient la liste des propriétés de la lambda (Nom , URI du code…)</p><p>6. Le nom de la fonction avec convention de nommage (domain-api-operation-domain-function).</p><p>7. Le chemin du handler et du point d’entrée de la fonction. Dans ce projet on le pointe vers le dossier dist qui contiendra notre javascript généré/compilé.⚡</p><p>8. Les permissions de notre fonction. Dans notre cas, on utiliser des opérations de CRUD vers le nom de la table précisée dans le paramètre du template (voir point N°1).</p><p>9. Cette section contient le type du déclencheur du lambda. Un déclencheur ou event peut être de type S3, SNS, SQS… voir ce <a href="https://docs.aws.amazon.com/fr_fr/lambda/latest/dg/lambda-services.html">lien</a> 👀.</p><p>10. Dans notre microservice, on expose des appels HTTP. Dans ce cas on spécifient le type avec la valeur API, en indiquant la méthode et l’API Gateway déclaré dans le point N°3.</p><p>Pour les autres fonctions lambda déclarées dans le template, cette configuration est identique.</p><p>Maintenant passons à la partie UserTable :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3N_n41-I0mL-Z0Jd" /></figure><p>11. Nous spécifions le nom de la table à créer avec comme valeur, le nom récupéré du paramètre du template (voir point N° 1)</p><p>12. La définition de la clé primaire de la table, sous forme d’une partition key PK, et d’un sort Key SK.</p><p>13. Chaque appel à la table DynamoDB est considéré comme une requête (Read request, Write request). Ces requêtes sont facturées à des prix différents selon les cas 💰. Par exemple pour les requêtes de lecture, le pricing diffère du cas d’usage (si fortement cohérentes, cohérente à terme, transactionnelle…) et selon la taille de l’item à récupérer. Toute requête utilise une unité appelée unité de capacité. Pour la lecture → RCU, pour l’ecriture → WCU. En mesurant le nombre de requêtes par seconde, on peut estimer nos RCU et WCU, et déduire la facturation de ces requêtes. Pour avoir plus d’infos, je vous invite à voir ce <a href="https://aws.amazon.com/fr/dynamodb/pricing/provisioned/">lien</a>. Dans notre SAM, on a configuré les RCU et WCU avec la valeur de 2.</p><p>14. On utilise les GSI (Global Secondary Indexes) qui sont considérés comme un autre moyen de projection de la table. Ils nous permettent d’éviter de lancer des requêtes SCAN sans passer par les PK qui parfois peuvent être couteuses, et lancer des requêtes Query sur d’autres champs que les PK.</p><p>Maintenant on va procéder au lancement de notre microservice 🐱‍🏍</p><h3>Lancement en Local</h3><p>Les opérations suivantes sont spécifiques pour un lancement en local. Si vous voulez tester dans votre compte AWS, passer directement au chapitre “Lancement SAM”</p><p>Configuration et lancement DynamoDB en local :</p><ol><li>Créer un network docker, pour isoler notre microservice avec la table dynamoDB.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*F2JgjcgdWN4WltiU" /></figure><p>2. Créer le docker-compose pour lancer le service DynamoDB en local</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VIa71u0UXewOdqoj" /></figure><p>3. Lancer la commande suivante pour démarrer notre docker-compose Dynamodb</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k5kpReFi4NsFCXLm" /></figure><p>4. Afin de vérifier le lancement de la base DynamoDB, vous pouvez utiliser l’outil AWS NoSQL Workbench. Cet outil est récupérable 👉 <a href="https://docs.aws.amazon.com/fr_fr/amazondynamodb/latest/developerguide/workbench.html">d’içi</a>. Il permet de concevoir et visualiser les tables et se connecter à notre base DynamoDB local 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iwB6Yit2I8UJA9DP" /></figure><p>5. Pour rajouter notre connexion local DynamoDB, cliquer sur Operation Builder, puis Add connection. Dans le formulaire de connexion, mettre les valeurs indiquées dans l’image, puis cliquer sur Connect (cela va ouvrir une connexion vers le container DynamoDB de l’étape 3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*MeyTv8lP9mWFD9N5" /></figure><p>6.Après que la connexion a été rajoutée dans la partie Actives connections. Cliquer sur Open pour visualiser le contenue de la base.👀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*Z1PtwYfbei2WsMwU" /></figure><p>Après ouverture de la connexion, vous allez remarquer que la base est vide, et qu’il n’y a pas encore de table DynamoDB. C’est normal on n’a pas encore créé de table, on procédera à sa création dans les étapes suivantes ⚡.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*0FFQcBFjLSBdk4gh" /></figure><p>7. Dans votre terminal, lancer la commande suivante pour créer la table user. Vous allez avoir un retour JSON indiquant que la table a été créé.👍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H293xwkhGVSTVdbX" /></figure><p>8. Actualiser la partie Tables, en cliquant sur le bouton rafraichir. Vous allez remarquer qu’une nouvelle table a été rajoutée. Notre table s’affiche bien mais sans données, car on n’a pas encore mis d’item. 📼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yf1vq80Cq7ctY9Lm" /></figure><p>Bravo 👏! vous avez configuré votre base DynamoDB, en créant le réseau Docker, la table user.</p><p>Maintenant nous allons démarrer 🥽 notre microservice avec SAM pour injecter des données, en lançant la commande suivante</p><p>Lancement SAM :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lP69CWXoREDnQwIs" /></figure><p>La commande sam local start-api permet de lancer un conteneur docker pour simuler un environnement lambda en local. Il a besoin des informations comme l’origine du template SAM, le numéro du port à exposer, et pour que notre table DynamoDB soit joignable, on spécifie le réseau docker aws-sam-local précédemment crée dans l’étape N° 1.</p><p>Aprés lancement de cette commande, ouvrez votre outil d’appels API préféré, dans cet exemple ça sera POSTMAN.</p><p>Créer une nouvelle requête de type POST en mettant les valeurs suivantes :</p><ul><li>URL : <a href="http://localhost:3000/user">http://localhost:3000/user</a></li><li>Exemple du Body :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qTaSp07_semFW1T8" /></figure><p>En background, la fonction lambda a été déclenchée, elle a généré un nouveau uuid 👆 et a créé l’item dans la table DynamoDB.</p><p>🧐Voyons ce qui s’est passé lors de cet appel dans la console SAM :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h6wjkpLTk4rL6gDN" /></figure><ol><li>Lors de l’appel, il y a eu un déclenchement de la fonction “user-create-function” et invocation de son point d’entrée ./app.handler</li><li>Récupération de l’image docker qui correspond à l’environnement de la fonction renseigné dans le template SAM, dans notre cas c’est le nodejs v10.x</li><li>Montage du volume dist de la fonction lambda dans le conteneur docker.</li><li>Affichage des logs qui correspond au lancement et fin d’exécution de la fonction déclenchée.📄</li></ol><p>On peut lancer les autres fonctions lambda du microservice. Par exemple récupération de tous les utilisateurs 👥:</p><p>Créer une nouvelle requête de type GET en mettant les valeurs suivantes :</p><ul><li>URL : <a href="http://localhost:3000/user">http://localhost:3000/user</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0kcMnfvFh8ocmSSt" /></figure><p>On peut aussi récupérer qu’un seul utilisateur avec la lambda get-user. Créer une nouvelle requête de type GET en mettant les valeurs suivantes :</p><ul><li>URL : <a href="http://localhost:3000/user">http://localhost:3000/user</a></li><li>Indiquer un id user dans le path aprés /user</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KrCp6LqlFDEsEfhc" /></figure><p>A présent, on a alimenté notre table DynamoDB. Actualiser la partie Tables, en cliquant sur le bouton rafraichir. Les enregistrements sont maintenant visibles 😁 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KLXat3t1sxVa0KRt" /></figure><p>👏Félicitations vous avez construit votre microservice Serverless. Je vous invite à trouver le code source sur mon <a href="https://github.com/hatim-heffoudhi/aws-sam-typescript-dynamodb-ioc">Github </a>✌</p><p>Préconisations :</p><p>Ci-dessous quelques préconisations que je tiens à partager avec vous pour la création d’un microservice Serverless :</p><ul><li>Bien structurer et organiser votre projet. Avoir une partie spécifique aux handlers, une partie qui regroupe les services transverses, et une partie pour les interactions avec les systèmes externes comme DynamoDB…</li><li>Implémenter le principe SOLID en limitant les responsabilités de vos classes/méthodes.</li><li>Eviter les duplications (DRY). Utiliser la partie SAM — Global et créer des classes utilitaires transverses aux fonctions lambda.</li><li>Se renseigner sur les <a href="https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html">quotas </a>des lambdas, car ça peut impacter le choix de votre architecture.</li><li>Ne pas mettre de règles métier dans les handlers, les externaliser dans la partie service.</li><li>Privilégiez les tests en local, sinon testez sur AWS si vous disposez d’un environnement dev.</li><li>Se renseigner sur la page lambda best practices lien <a href="https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html">içi</a>.</li></ul><p>Merci pour votre lecture 👍. Dans la troisième partie on va aborder le déploiement de ce microservice avec Gitlab et avec la suite AWS CICD 🔥 !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90913966f7c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construire un microservice serverless & le déployer sur AWS (part 1)]]></title>
            <link>https://medium.com/@hatim.heff/construire-un-microservice-serverless-le-d%C3%A9ployer-sur-aws-part-1-6b34df08adad?source=rss-74ac865be93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b34df08adad</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[HATIM HEFFOUDHI]]></dc:creator>
            <pubDate>Wed, 03 Nov 2021 10:46:47 GMT</pubDate>
            <atom:updated>2021-11-03T10:46:47.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*LZvvslQDXDjdALykNd4XaQ.png" /></figure><p>Bienvenue dans le premier article d’une série consacrée au Cloud Serverless. Nous allons voir ensemble comment créer et déployer un microservice Serverless sur AWS.</p><p>Je partagerai ici mes retours d’expérience, quelques bonnes pratiques à l’usage des développeurs et bien sûr… du code !</p><p>Ce que j’ai pu vivre sur le terrain, chez mes clients, fera sans doute écho à vos propres enjeux. N’hésitez pas à réagir en commentaires, je suis preneur de ces échanges.</p><p>A l’issue de la série, vous maîtrisez ces 8 étapes :</p><ul><li>Concevoir le socle d’un microservice Serverless;</li><li>Créer et isoler vos lambdas AWS;</li><li>Insérer/récupérer les données de vos tables DynamoDB ;</li><li>Lancer et débugger en local le microservice serverless;</li><li>Sécuriser et récupérer vos variables d’environnements;</li><li>Lancer un déploiement avec Gitlab CI/CD;</li><li>Faire un déploiement avec la suite DEVOPS — AWS CI/CD.</li></ul><p>Nous allons répondre ensemble à toutes les questions portant sur la modélisation et sur le choix à faire entre une seule Lambda ou plusieurs Lambdas par projet.</p><h4>Mais avant cela, jetons un coup d’œil dans le rétroviseur</h4><p>Si l’on compare le développement logiciel à l’architecture, on peut en référer aux “monolithes” des années 1990 et 2000 : à l’époque, on construisait des ensembles avec des briques interdépendantes. Tout était connecté.</p><p>On s’est rendu compte par la suite que cela rendait les choses très compliquées pour la maintenance d’une application et pour n’importe quel développement ultérieur. Ainsi, pour modifier une seule partie du système, on était obligé de toucher à l’ensemble des autres couches.</p><p>Alors, on a découpé les briques, de plus en plus finement, pour parvenir à une forme “micro” du service et s’affranchir de la dépendance au reste du système, comme résumé sur ce schéma :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*XoFYE1QxNIoZ91lO" /></figure><blockquote><em>Chacun de ces microservices remplit une seule mission, travaille dans son propre environnement et stocke ses propres données.</em></blockquote><p>Les microservices apportent quatre avantages majeurs :</p><ul><li>Rapidité des mises en place;</li><li>Faible coût;</li><li>Evolutivité;</li><li>Performance.</li></ul><p>Attention, malgré le terme “micro”, les micro-services ne sont pas forcément… petits ! On les qualifie de “micro” parce qu’ils sont une partie autonome d’un ensemble plus vaste.</p><p>Pour l’utilisateur, tout cela est invisible : on a séparé le “front end” (ce que le client voit) du “back end”. Aujourd’hui, quand on touche au front end, on ne touche plus aux microservices qui sont logés dans le back end, sous forme d’APIs agnostiques.</p><p>En termes d’organisation, cela permet d’avoir différentes équipes travaillant simultanément sur “leur” microservice, avec des langages informatiques différents.</p><p>Et en termes logistiques, pour faire tourner ces microservices, on a créé des serveurs capables de résister à des sollicitations importantes. On a ainsi établi une double scalabilité : verticale (pour tenir la charge, augmentation CPU, RAM…) et horizontale (on duplique l’API sur différents serveurs).</p><p>Vous l’avez compris : on réduit les coûts d’infrastructure puisqu’on peut allouer à chaque microservice la juste quantité de ressources.</p><p>Même chose en cas de panne : on identifie le microservice défaillant et on le corrige rapidement.</p><p>Et pour finir… on est passé du serveur robuste à un monde Serverless (sans serveur) ! C’est là qu’interviennent les fournisseurs du Cloud. On peut désormais confier au prestataire Cloud la gestion des ressources nécessaires au fonctionnement de ces microservices utilisés à la demande, pour se libérer des contraintes de gestion de l’infrastructure, laissant les équipes se focaliser sur la valeur métier, le développement des fonctionnalités et les livraisons.</p><blockquote><em>En résumé, Serverless nous permet d’exécuter du code à la demande suivant des déclencheurs prédéfinis (Appel HTTP, Dépôt d’un fichier, Alarme déclenchée…), de gérer du stockage et d’évoluer “scale Out” (scalabilité horizontale). Le tout sans aucune administration ou maintenance de l’infrastructure !</em></blockquote><p>Dans cette série, AWS est le Cloud Provider — et notre microservice serverless se composera de 3 AWS Lambda desservies par une Amazon API Gateway de type REST API et les données seront stockées dans une table Serverless Amazon DynamoDB, le tout déployé via l’outil AWS SAM. Pour mémoire :</p><p>AWS Lambda est un service Serverless de calcul qui nous permet d’exécuter du code sans nécessiter le provisionnement ni la gestion de serveurs. Le code est exécuté à la demande et seulement lorsque cela est nécessaire sans oublier qu’il se met à l’échelle de façon automatique.</p><p>Amazon DynamoDB est un service Serverless de base de données NoSQL qui nous permet de créer des items dans des tables ( clé, valeur) , offrant des performances rapides et prévisibles tout en offrant une évolutivité transparente suivant le trafic et le nombre de Read/Write demandé.</p><p>Amazon API Gateway est un service Serverless agissant comme une « porte d’entrée » qui permet de créer, publier, gérer, surveiller et de sécuriser les API REST, HTTP et WebSocket à n’importe quelle échelle, et de gérer aussi les autorisations, contrôle des accès des appels effectués aux APIs ainsi que la gestion de leur version (Stages).</p><p>AWS SAM Serverless Application Model est un alias de CloudFormation qui nous permettra de gérer et de déployer des ressources Serverless dans un template Yaml (identique aux templates CloudFormation) et aussi de pouvoir lancer et tester nos Lambdas en local via un docker container.</p><p>Une vue d’ensemble du résultat :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WIUwZ3m4pwjkFdUN" /></figure><h3>Les pré-requis pour commencer : 4 installations avant de vous lancer</h3><ul><li><a href="https://portal.aws.amazon.com/billing/signup#/start">Créer un compte AWS</a></li><li><a href="https://nodejs.org/en/">Installation de node.js (incluant le NPM package management tool)</a></li><li><a href="https://hub.docker.com/search/?type=edition&amp;offering=community">Installation Docker C.E</a></li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">Installation de AWS CLI</a></li><li><a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html">Installation de AWS SAM CLI</a></li></ul><p>Une fois les installations terminées, validez-les avec les commandes suivantes :</p><ul><li>Docker</li></ul><pre>$ docker --version </pre><pre>Docker version 20.10.3, build 48d30b5</pre><ul><li>NPM</li></ul><pre>$ npm --version</pre><pre>6.14.4</pre><ul><li>AWS</li></ul><p>Pour AWS, afin d’utiliser la CLI, vous auriez besoin de créer des identifiants :</p><p>Pour cela, accédez au service IAM, cliquez sur l’onglet Security credentials de votre utilisateur IAM :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*03xRtkj5zLVZcczF" /></figure><p>Pour générer de nouveaux identifiants CLI (access key), cliquez sur le bouton “Create access key” :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vozDLrMfzLPJFfJ-" /></figure><p>AWS va générer de nouveaux comptes CLI que vous pouvez télécharger ou récupérer depuis la console , /!\ ces comptes sont à usage unique, en cas de fermeture de la fenêtre vous devez recommencer cette étape :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EkUoAyeUedwEiia5" /></figure><p>Accédez à votre terminal, et tapez la commande suivante en renseignant les valeurs précédentes :</p><pre>$ aws configure</pre><pre>AWS Access Key ID [None]: &lt;AWS_ACCESS_KEY_ID&gt;<br>AWS Secret Access Key [None]: &lt;AWS_SECRET_ACCESS_KEY&gt;<br>Default region name [None]: &lt;REGION&gt; <br>Default output format [None]:</pre><p>Testez avec la commande suivante, si tout est ok vous obtiendrez ce résultat :</p><pre>$ aws sts get-caller-identity<br></pre><pre>{<br>    &quot;UserId&quot;: &quot;************&quot;,<br>    &quot;Account&quot;: &quot;***********&quot;,<br>    &quot;Arn&quot;: &quot;arn:aws:iam::***********:user/************&quot;</pre><pre>}</pre><ul><li>SAM</li></ul><pre>$ sam --version</pre><pre>SAM CLI, version 1.18.2</pre><p>Parfait ! Dans le prochain article, nous allons mettre la main à la pâte et commencer à créer notre socle technique Serverless…</p><p>A suivre Organisation et mise en place du socle de mon microservice serverless (part 2)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b34df08adad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>