<?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 Koby Almog on Medium]]></title>
        <description><![CDATA[Stories by Koby Almog on Medium]]></description>
        <link>https://medium.com/@kobyal?source=rss-38b993992beb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*baU_n8QtzzgrDBlUL3_yYQ.png</url>
            <title>Stories by Koby Almog on Medium</title>
            <link>https://medium.com/@kobyal?source=rss-38b993992beb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:10:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kobyal/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[I Built an AI Meeting Recorder. Now Every Meeting and Lecture Ends as a PDF.]]></title>
            <link>https://medium.com/@kobyal/i-built-an-ai-meeting-recorder-now-every-meeting-and-lecture-ends-as-a-pdf-30f5a8840ceb?source=rss-38b993992beb------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f5a8840ceb</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Koby Almog]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 07:33:45 GMT</pubDate>
            <atom:updated>2026-10-21T07:33:45.386Z</atom:updated>
            <content:encoded><![CDATA[<h4>One open-source pipeline with two doors: paste a talk link or just join a Zoom, and get a document with the slides, the decisions and who owns what. How it works, what it saves, and what it got wrong.</h4><figure><img alt="Erik Schluntz’s “Vibe coding in prod” talk (31:04) in a video player and a Zoom meeting window, each with a hand-drawn arrow to a stack of PDF pages; a note says “both end as a PDF”." src="https://cdn-images-1.medium.com/max/1024/1*oH22JVjUevsG0N57pGIt_w.png" /><figcaption>A talk I saved for later and a meeting I was in. Both end the same way.</figcaption></figure><p>Two kinds of recordings pile up in my life.</p><p>The first is the talk. Someone posts “skip Netflix tonight, watch this one-hour session”, I save it, and I never watch it. My saved list on X is a graveyard of good intentions.</p><p>The second is the meeting. Forty-five minutes on Zoom, three decisions, five tasks. By Thursday nobody remembers who agreed to what, and there is no recording to go back to anyway.</p><p>For the past few weeks both end the same way. I paste a link, or I just join the call, and a few minutes later I have a PDF: the speaker’s slides or the screens people shared, the argument or the decisions, and who owns what. I read it in five minutes. I’ve stopped taking notes.</p><p>Here is what you get, how it works, and how I use it day to day. The lessons from building it come at the end.</p><h3>You get a document, not a transcript</h3><p>A transcript is a wall of text. Nobody reads it, which is why most “AI notes” are skimmed once and forgotten. The pipeline produces a typeset document a person would actually read.</p><figure><img alt="Left: three pages of a Hebrew review of a 31-minute talk with the speaker’s slides, “10 pages”. Right: three pages of a meeting PDF, “minutes after the call”. Under each, a checklist of what’s inside." src="https://cdn-images-1.medium.com/max/1024/1*YEaT-7W7JQ7CJe2qhrXWOg.png" /><figcaption>Same pipeline, two kinds of output. The talk keeps the speaker’s own slides; the meeting keeps the decisions and the owners.</figcaption></figure><p><strong>From a talk</strong> you get the speaker’s own slides, pulled out of the video, each one placed next to the paragraph that explains it. Then the argument section by section, the quotes worth keeping, and a short “what wasn’t said” part. Erik Schluntz’s 31-minute talk on vibe coding in production became a 10-page Hebrew review. It can write in English too.</p><p><strong>From a meeting</strong> you get the discussion with the shared screens in place, a list of decisions, and tasks grouped by owner. Plus a small record.json that the next Claude Code session can read, so &quot;what did we decide about the portal?&quot; has an answer next week.</p><p><strong>What it saves</strong> is mostly attention. I don’t rewatch recordings, I don’t take notes during calls, and I don’t scroll through Slack to find who said they’d handle it. The talk side has grown into a public library of <a href="https://aibriefing.dev/library/">60 write-ups</a>, free to read, filtered by topic and by how much time you have.</p><h3>One pipeline, two doors</h3><p>The two jobs share most of the work. Only the way in is different.</p><figure><img alt="Hand-drawn pipeline. Door 1: paste a link, fetch, slides. Door 2: join a Zoom, capture, who and what. Both feed transcribe (local), write (cloud LLM, the only step that leaves the laptop) and render, which outputs a talk review or a meeting PDF with record.json." src="https://cdn-images-1.medium.com/max/1024/1*6rHzj4Di2mQojqB4XaTBuA.png" /><figcaption>Two ways in, one shared middle. Only the writing step leaves the laptop.</figcaption></figure><p><strong>The shared middle</strong> has three steps:</p><ul><li><strong>Transcribe.</strong> Whisper runs locally (mlx-whisper on Apple Silicon, faster-whisper on CPU anywhere else). For Hebrew it uses <a href="https://huggingface.co/ivrit-ai">ivrit.ai</a>’s fine-tune of large-v3-turbo, which fixed most of the garbled words the base model produced, at the same speed.</li><li><strong>Write.</strong> Claude Code reads the transcript and the pictures and writes the content: sections, quotes, decisions, owners. A skill file tells it what a good review looks like. This is the judgement step, and the only one that sends anything off the laptop.</li><li><strong>Render.</strong> A script typesets DOCX and PDF. Hebrew in Word turned out to be three separate bugs (property order, complex-script fonts, and alignment that flips inside right-to-left paragraphs), so the renderer handles them instead of hoping.</li></ul><h4>Door 1: paste a link</h4><p><strong>Fetch</strong> takes a YouTube link, an X post, a conference livestream page or a local file, and downloads the recording at a size where slides are readable (no wider than 1280 px; 1080p costs twice the time for nothing).</p><p><strong>Slides</strong> is where talks get interesting. One pass of scene detection over the video catches every change of picture, near-duplicates are dropped, and the slide rectangle is cropped out of the stage shot.</p><figure><img alt="A grid of 30 of the 72 frames kept from a 31-minute talk, one slide (“This is not a new problem”) picked, and that slide placed in a page of the Hebrew write-up." src="https://cdn-images-1.medium.com/max/1024/1*gAGU_kWIBUkUkD-vph8BYw.png" /><figcaption>72 frames kept from a 31-minute talk. Each slide lands next to the paragraph that explains it.</figcaption></figure><p><strong>One rule for X posts:</strong> reposts often come with a bait caption, so the title, speakers and claims come from the transcript and slides, never from the post. (More on that below.)</p><figure><img alt="The aibriefing.dev talk library in a browser window, with the length filters circled." src="https://cdn-images-1.medium.com/max/1024/1*sxpUVMhL8RZAOTQk_ZiLWA.png" /><figcaption>The talk side today: 60 write-ups at aibriefing.dev, filtered by topic and by length.</figcaption></figure><h4>Door 2: join a Zoom</h4><p>The meeting door is more work, because there is no file to download. The pipeline has to sit in the meeting with me.</p><p><strong>Capture.</strong> Before a call I tell Claude Code to record my next Zoom. A background loop waits for Zoom’s meeting process; when I join, it starts recording Zoom’s audio only (OBS, in application-capture mode) and grabs the Zoom window every 3 seconds. It records the window, not the screen, so I can keep working in other apps. When the meeting process exits, it stops.</p><figure><img alt="Timeline of a live capture: audio and window-grab lanes, a transcription check at 0:35, health checks every 3 minutes, stop when Zoom exits." src="https://cdn-images-1.medium.com/max/1024/1*wi_SpcH9bJca3CmDScGihg.png" /><figcaption>Two streams, started and stopped by Zoom’s own meeting process, and checked while they run.</figcaption></figure><p><strong>Who’s talking.</strong> I skipped audio diarization, which gives you “Speaker 3” instead of a name. Zoom already knows who is talking: the active speaker’s tile gets a green border, and every tile carries a display name. The pipeline finds the green rectangle in each window grab, reads the name with macOS Vision OCR, and marks each change in the transcript as &lt;&lt;Name&gt;&gt;. When nobody is green, it keeps the last name with a question mark.</p><figure><img alt="Animation: a meeting window where a green border moves between participant tiles while transcript lines get tagged with names; the last line, with no green tile, gets an uncertain &lt;&lt;Dana?&gt;&gt; label." src="https://cdn-images-1.medium.com/max/1024/1*bfPA0TjUxuJafxM8a7H6ng.gif" /><figcaption>The green border moves, the transcript gets tagged. When nobody is green, the label says it’s a guess.</figcaption></figure><p><strong>What was shared.</strong> Conference scene detection fails on meetings: Zoom’s interface fills most of the frame, so two different shared screens look the same, while moving faces look new every few seconds. A separate picker finds the shared-content rectangle in each frame, crops to it and compares only the crops. On real recordings, an hour of screen-sharing went from 1 picture to 5, and a webinar from 3 to 10.</p><figure><img alt="Seven meeting-window grabs, two with no shared screen; the shared area is outlined, and two cropped pictures come out: a chart and a sprint board." src="https://cdn-images-1.medium.com/max/1024/1*AOWu8ro6FKoo6INOf29FoA.png" /><figcaption>Seven window grabs in, two pictures out. Compare the shared part, not the whole window.</figcaption></figure><p><strong>Who’s who.</strong> A recording can’t tell you how a name is spelled, what a nickname means, or whether to write <em>he said</em> or <em>she said</em> in Hebrew. So there is a people file: plain Markdown, one section per person, kept outside any repo.</p><pre>## Dana Cohen<br>- zoom: Dana.Cohen<br>- gender: f<br>- aka: Dana, Danna<br>- team: Platform<br>- role: team lead; hosts the weekly status round<br>- works on: CI runners, Kubernetes upgrades</pre><figure><img alt="A PEOPLE.md file in an editor with zoom, gender, aka, role and works-on fields, annotated with what each one is used for." src="https://cdn-images-1.medium.com/max/1024/1*KZRKq5g7lmbArVH3zbkNAQ.png" /><figcaption>What the recording can’t tell you, in one private file. This is the repo’s fictional example.</figcaption></figure><p>Names and nicknames go into Whisper’s prompt so they come out spelled right. The Zoom name maps a tile to one canonical name. Gender decides Hebrew verb forms, and ? means write it neutrally.</p><p><strong>The meeting PDF</strong> puts each shared screen next to the discussion about it, lists the decisions, and groups the tasks by owner. People marked ? in the people file are written about in neutral language.</p><figure><img alt="Two pages of a fictional Hebrew meeting PDF: a chart from the shared screen, a gender-neutral note about Alex, and tasks by owner." src="https://cdn-images-1.medium.com/max/1024/1*Mh4BL9g1QiWFH2JHMQp62A.png" /><figcaption>A fictional weekly status round, rendered by the real pipeline: the shared chart in place, a gender-neutral line about Alex, tasks by owner.</figcaption></figure><p><strong>The record.</strong> Besides the PDF, every meeting writes a record.json (participants, summary, decisions, actions with owner and status, open questions) and one row in an INDEX.md. A later Claude Code session reads the index, opens the right record, and answers from it.</p><figure><img alt="A record.json and an INDEX.md row next to a later Claude Code session answering “what did we decide about the portal, and who owns it?”" src="https://cdn-images-1.medium.com/max/1024/1*w8NJlBrqKeklq2jhJE8cTA.png" /><figcaption>One index row per meeting is enough for a later session to find what was decided and who owns it.</figcaption></figure><h4>How I actually use it</h4><p>For a talk, I type one line in Claude Code: <em>make a PDF review of</em> and the link. For a meeting, I say <em>record my next Zoom</em> before the call and ask for the PDF when it ends. That’s the whole interface.</p><figure><img alt="A terminal running Claude Code: “make a PDF review of” a talk link produces a 10-page PDF; “record my next Zoom” waits, records, and produces a meeting PDF, record.json and INDEX.md. Each result points to a PDF page." src="https://cdn-images-1.medium.com/max/1024/1*GkWyE8-RflfFvWBjpDpdfQ.png" /><figcaption>Two sentences in Claude Code, two documents. (Output shortened.)</figcaption></figure><h3>A week with it</h3><p>A typical week looks like this:</p><ul><li><strong>Sunday</strong>, a weekly status round where everyone reports in turn. The PDF has a section per person and every task by owner.</li><li><strong>Tuesday</strong>, a stand-up. The decisions and the release plan are ready a few minutes after the call.</li><li><strong>Wednesday</strong>, a planning meeting where someone shares a spreadsheet for a long stretch. The PDF has the screenshots, next to the discussion about them.</li><li><strong>Thursday evening</strong>, two talks from my feed that I would never have watched. A few minutes of reading each, instead of an hour of video.</li></ul><p>The meeting PDFs are what changed my work. The talk PDFs are what changed my evenings.</p><h3>What it got wrong</h3><p>Every week the pipeline got better at listening. Most of its mistakes were somewhere else. Six of them taught me something that applies to any AI note-taker, including the summary button in Zoom.</p><p><strong>1. The first name in a turn is the person being asked.</strong> In a stand-up I said “I’m off Sunday and Monday, and Tuesday is election day anyway.” The summary gave my vacation to a colleague. My own tile was hidden, so nothing turned green when I spoke; the timeline carried the previous speaker forward with a ?; and the turn had opened with &quot;Yossi, Koby?&quot;, a question to both of us. The model joined the first name to the first-person sentence.</p><figure><img alt="A transcript turn starting “Yossi, Koby?” followed by “I’m off Sunday and Monday”; the first summary gives the vacation to Yossi, the fixed one to Koby." src="https://cdn-images-1.medium.com/max/1024/1*n_zEYccUZWD9EV4XvfUlPA.png" /><figcaption>Every step did what it was built to do. The result was still wrong, and it read perfectly.</figcaption></figure><blockquote><em>A summarizing tool doesn’t fail loudly when it’s wrong. It hands you something that looks finished.</em></blockquote><p>The fix was four lines in the skill: a name at the start of a turn is usually the person addressed; “I” and “my” belong to whoever is actually speaking; a ? label is a guess, so check before attributing anything personal; and the person recording is a participant too. <strong>Takeaway:</strong> search any AI summary for &quot;I&quot; and &quot;my&quot;, and check who it says said them.</p><p><strong>2. Hebrew verbs have gender, and the model guessed.</strong> A male colleague whose first name reads as female in Hebrew became a woman for a whole report. Whisper wasn’t the problem; the model writing third-person sentences was, and it guessed from the name. That’s why the people file has a gender field. <strong>Takeaway:</strong> gendered language and job titles should come from people, not guesses.</p><p><strong>3. Whisper heard “thank you” in a silent room.</strong> A broken capture mode recorded a flat −42 dB of near-silence, and Whisper turned it into “תודה רבה” (“thank you very much”). Both the meter and the transcript looked alive. Now the recorder transcribes a 25-second slice about 35 seconds in and checks for real words. <strong>Takeaway:</strong> check a recording by its words, not its volume.</p><p><strong>4. macOS took a permission back.</strong> My first end trigger asked macOS whether the meeting window still existed. Mid-meeting, macOS revoked that permission, the check saw “no window”, and the recording stopped after 49 seconds. Now the trigger is Zoom’s own meeting process, and a health check every 3 minutes watches that the files keep growing. <strong>Takeaway:</strong> a red recording light is not proof.</p><p><strong>5. The caption lied about the speaker.</strong> “A talk by the head of Claude Code” turned out to be Erik Schluntz on vibe coding in production. “An interview with Dario Amodei” was a 49-minute documentary profile of Anthropic. <strong>Takeaway:</strong> if an AI summary got the speaker’s name from the caption, it’s a claim, not a fact.</p><p><strong>6. Every shared screen looked the same.</strong> That’s the picker from Door 2. <strong>Takeaway:</strong> a summary without what was on screen loses half the meeting.</p><figure><img alt="A card: “Before you forward AI meeting notes”, seven numbered checks." src="https://cdn-images-1.medium.com/max/1024/1*AxUwE9s2uhOMPsgqWwZElA.png" /><figcaption>Seven checks before you forward AI meeting notes. Works for any tool.</figcaption></figure><h3>Limits, and the questions to ask first</h3><p><strong>Consent comes before engineering.</strong> I record only meetings where recording is allowed and the people in them know. The tool doesn’t hide, and anyone in the meeting can ask for the notes. If your team hasn’t agreed, don’t record.</p><p><strong>It’s not fully local.</strong> Transcription is. The writing step sends the transcript, the chosen pictures and the people file to an LLM. For work, use the model access your organization approves, and treat the transcript as the sensitive document it is.</p><p><strong>Speakers are still sometimes a guess.</strong> Across four recorded meetings, 6% of speaker turns carried a ?. In the one where my own tile was hidden it was 21%, and that&#39;s where the vacation lived.</p><p><strong>The people file is evidence, not proof.</strong> It’s reliable for names and gender. “Yossi owns the portal” makes it likely the portal update is his, but if the timeline says Dana was talking, Dana was talking.</p><p><strong>Live capture is macOS only.</strong> Talks work anywhere Python, ffmpeg and LibreOffice run. Recording a live Zoom needs a Mac today.</p><p>The last step is still a person reading the PDF before forwarding it.</p><h3>Try it</h3><pre>brew install ffmpeg yt-dlp libreoffice poppler<br>git clone https://github.com/kobyal/recording-to-pdf ~/.claude/skills/recording-to-pdf<br>cd ~/.claude/skills/recording-to-pdf &amp;&amp; python3.12 -m venv .venv &amp;&amp; .venv/bin/pip install -r requirements.txt<br># then in Claude Code: &quot;Make a PDF review of https://www.youtube.com/watch?v=...&quot;</pre><p>Start with a talk: pick the one sitting longest in your “watch later” list and turn it into a PDF. For meetings, copy examples/people.example.md somewhere outside the repo, fill in your people, and point R2R_PEOPLE at it.</p><p>The code is MIT-licensed and free. You pay for whatever model does the writing.</p><p>And a question I’d like real answers to: <strong>what would you rather read than watch, a talk or a meeting?</strong> And if you already use AI meeting notes at work, how do you check who said what?</p><h3>One last thing.</h3><p>I built this to stop watching conference talks. It ended up sitting in my meetings.</p><p>The recording tells you what was said. The PDF is how you actually find it again.</p><p><strong>Resources</strong></p><ul><li>Code: <a href="https://github.com/kobyal/recording-to-pdf">github.com/kobyal/recording-to-pdf</a> (MIT)</li><li>The first article: <a href="https://medium.com/@kobyal/how-i-turned-47-aws-summit-talks-into-pdfs-a-4-stage-open-source-pipeline-0aeb2fa34ace">How I Turned 47 AWS Summit Talks Into PDFs</a></li><li>The talk library: <a href="https://aibriefing.dev/library/">aibriefing.dev/library</a></li><li>Hebrew Whisper models by ivrit.ai: <a href="https://huggingface.co/ivrit-ai">huggingface.co/ivrit-ai</a></li></ul><p><em>Koby Almog is an AI tech lead in Israel and writes about making AI tools useful in regulated environments. Personal project; opinions his own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f5a8840ceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your support group asks the same 20 questions.]]></title>
            <link>https://medium.com/@kobyal/your-support-group-asks-the-same-20-questions-057456740dfa?source=rss-38b993992beb------2</link>
            <guid isPermaLink="false">https://medium.com/p/057456740dfa</guid>
            <category><![CDATA[whatsapp]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Koby Almog]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 14:17:06 GMT</pubDate>
            <atom:updated>2026-09-24T14:17:06.351Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your support group asks the same 20 questions. I built a WhatsApp bot that answers them from a knowledge base, on AWS, for $18 a month. Here is how.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zco2R5aaskyB7F_YESILNw.png" /></figure><p><em>Figure 1. The whole system: one WhatsApp account and a linked-device session into an EC2 listener, a Lambda brain that calls Bedrock, a DynamoDB table per group, and a curator that can only read the log.</em></p><p>The same questions keep coming back. <em>It logs me out every morning.</em> <em>How do I install this on Windows?</em> <em>Why is the proxy blocking me?</em> Someone who knows the answer types it for the fifteenth time, or pastes a link nobody reads, or is asleep.</p><p>That is what made me build the bot. About 120 developers at a bank, onboarding onto a new AI coding tool, all in one WhatsApp group, asking the same twenty things. The bot answers them from a knowledge base that people wrote and verified — and when nothing fits well enough, it says nothing at all.</p><p>It has been running since the summer of 2026. A second division asked for one in September, with its own knowledge base. Then people started messaging it privately. This is the build log and the recipe: what it does, the four things that were harder than they looked, and how to stand one up yourself.</p><p><strong>TL;DR</strong> A small EC2 instance holds the WhatsApp session. A Lambda asks a model <em>which</em> human-written answer fits and sends it word for word if confidence clears 0.90, asks one of three fixed questions between 0.70 and 0.90, and says nothing otherwise. It serves two pilot groups with separate knowledge bases, answers members in private chat, and a separate layer harvests confirmed answers from the log into the KB behind gates that run in code. A few weeks in, the lessons that mattered were about identity and structure, not prompts. Repo: <a href="https://github.com/kobyal/whatsapp-kb-bot">github.com/kobyal/whatsapp-kb-bot</a>.</p><p><em>Personal project, my own time and my own AWS account. Not a product of my employer, not endorsed by WhatsApp, and it uses an unofficial WhatsApp client; section 1 explains what that means before you decide whether to run one.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXYJXuLu0HpE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXYJXuLu0HpE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXYJXuLu0HpE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b97e3d0723ea11985fde839a469929d/href">https://medium.com/media/4b97e3d0723ea11985fde839a469929d/href</a></iframe><p><em>A 44-second demo, narrated, with fictional people and a generic chat UI. A Hebrew cut is in the repo, under docs/media/demo/.</em></p><p>This is the story of that bot growing from “answers a question” to “knows when to be quiet”, and of the template version that is public. I will cover:</p><ol><li>The two constraints that decide the architecture before you write a line</li><li>What the bot does, and why silence is one of its three outcomes</li><li>The morning it talked over the humans, and three fixes that were not prompt wording</li><li>Why the <em>order</em> of a list in a JSON file decided whether a question got answered</li><li>Two groups, one bot, and what happened when people wanted to DM it</li><li>The curator: letting the bot learn from the log without letting it write</li><li>A 60-second stall that looked exactly like silence</li><li>Costs, risks, what is next, and what I would do differently</li><li>How to build one yourself, step by step, starting with the knowledge base</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hq7K12oAXB12Ft95jZrE3g.png" /></figure><p><em>The demo’s title card. Everything in this article is in service of that one sentence.</em></p><h3>1. Two constraints you cannot design around</h3><h3>WhatsApp has no official way into a group</h3><p>The WhatsApp Business Cloud API is the compliant route, and if your bot is a 1:1 customer-service line, use it. But if the bot needs to live <em>inside a group that already exists</em>, read the Groups API documentation: as of writing, a group created through the API is capped at <strong>8 participants</strong>, the business must create the group itself, and it cannot join a group a person created. Registering a number with the Cloud API also deletes that number’s normal WhatsApp account. Meta’s new setup-automation tooling, announced this month, changes none of those limits.</p><p>So for a community group of a hundred people, the only technical route is an <strong>unofficial multi-device client</strong>: a library that speaks the WhatsApp Web protocol and appears as a linked device, like WhatsApp Desktop does. I use <a href="https://github.com/WhiskeySockets/Baileys">Baileys</a>. It works well. It is also against WhatsApp’s terms of service, and numbers running it do get banned.</p><p>I will not pretend otherwise, so here is how I live with it. A <strong>dedicated prepaid SIM</strong> in an old Android on Wi-Fi, never my own number. <strong>Reply-only</strong>: the bot never starts a conversation and never messages a stranger. <strong>Human pacing</strong>: a random 1.5 to 4 second delay before every reply. Nothing I care about attached to that number. If it is banned, I lose a cheap SIM; if it were my number, I would lose my chats, my groups and my family with no appeal process that works. People make that mistake exactly once, so the repo has a whole document on picking the SIM.</p><p>A linked device holds a persistent WebSocket and Lambda dies after 15 minutes, so the bot is two pieces: a tiny always-on <strong>listener</strong> on EC2 that knows nothing about the knowledge base, and a <strong>brain</strong> in Lambda that knows nothing about WhatsApp. JSON in, JSON out. Everything below happens in the brain, which is why almost none of it is WhatsApp-specific.</p><h3>The model routes. It does not write.</h3><p>This is the rule I would defend hardest, and every feature in this article was built inside it. The bot sends a knowledge-base entry’s answer exactly as a human wrote and verified it. The model&#39;s only job is to pick <em>which</em> entry.</p><p>In a group, a confident wrong answer is the most expensive thing a bot can do. Everyone reads it. It looks official. Someone follows it. Bounding the model to “pick an entry” bounds the failure to “wrong entry”, and a confidence floor handles that. “Plausible invented steps” stops being a failure mode. Even the three clarifying questions are hard-coded strings; the model returns a <em>key</em>, and an unknown key falls back to the one asking for the exact error text.</p><h3>2. What the bot does, and why silence is an outcome</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49gFZxDKIuHFHcV6OskR1w.png" /></figure><p><em>Figure 2. Three outcomes, and most paths lead to the grey one.</em></p><p><strong>Screen first.</strong> Before any matching, a short prompt with no catalogue in it answers one question: <em>is this a request for help at all, and is it in our domain?</em> When I replayed 326 real group messages through an early version, 21 of the 64 confident answers landed on messages that were never questions: someone posting a fix for others, a staff announcement, “same here”, one human asking another. The bot was talking over the humans doing triage.</p><p><strong>Then classify.</strong> The model sees a catalogue of every entry’s id, phrasings, error strings and a short gloss, never the answers, and returns {&quot;id&quot;: ..., &quot;confidence&quot;: 0.93}.</p><p><strong>Then one of three outcomes.</strong></p><ul><li><strong>≥ 0.90</strong> → <strong>Answer</strong>, verbatim. The model only emits 0.92 and 0.95 above this line; measured after the change, 0% of them were wrong</li><li><strong>0.70–0.90</strong> → <strong>Clarify</strong>: one of three fixed questions, once per person per 30 minutes. The 0.85 bucket was right 3 times in 39. A bucket that names an entry and is wrong 92% of the time is exactly where one concrete question is the honest response</li><li><strong>below 0.70, not a request, off-domain, or “is the service down?”</strong> → <strong>Silence</strong>. A knowledge base cannot answer “is it down for everyone?”, and asking “which environment?” sets an expectation it cannot meet</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mg99etRO9BM286uW-m6EIQ.png" /></figure><p><em>From the demo: a miss. The bot posts nothing, on purpose.</em></p><p>My first floor was 0.80. When an independent model graded every confident answer in the replay, the wrong-or-partial rate was <strong>42%</strong>. Raising the floor to 0.90 and routing the 0.85 bucket to a question took it to <strong>6%</strong>. The bot answered fewer, better questions, and in a 120-person group that is the trade you want every time.</p><p>Silence is not the bot failing. It is the bot deciding a human will do this better, which in a group full of humans is usually true. It is also <em>readable</em>: people learn that the bot speaks only when it is sure, which is the only reputation worth having.</p><p>The clarify rate limit is a safety property, not a nicety. WhatsApp delivers bursts, and the first real end-to-end run sent three identical clarifying questions within one second from concurrent invocations. Comparing “now” to a stored timestamp is not a rate limit under concurrency; the limit now lives in a DynamoDB conditional write, so exactly one caller can win it.</p><h3>3. The morning the bot talked over the humans</h3><p>The second pilot group has something the first does not: a staffed support bench, two people whose job is to answer. On the first morning back from a holiday, my bot interrupted both of them.</p><p>At 08:33 the division’s product owner asked a user, “Is there a bar at the top of Outlook asking you to sign in?” The bot replied to <em>her</em> with a clarifying question. Ten minutes later her colleague, quoting a user, asked “drag it to the mail icon in the taskbar, or into the open window?” The bot asked <em>him</em> for the exact error text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DS8lbxL4575jgsEnUVlPRg.png" /></figure><p><em>From the demo: a covered question in the group. (The real thread from that morning is a bank group, so it stays out of this article.)</em></p><p>Both are textbook “second person aimed at a human”, and the screening prompt already had a rule for exactly that. It had been right for two weeks and still did not fire. The reason was not in the prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tz7df44DS8piyFEnZ-dsXQ.png" /></figure><p><em>Figure 3. The prompt was fine. The input was a bare string.</em></p><p><strong>The brain only ever saw the text.</strong> The listener forwarded {text, group, participant}. Nothing about who the sender was in that room, whom they were replying to, or whether a human had just picked the question up. No prompt can recover information that was never in the input. So the three fixes are all <strong>identity or structure, never model judgement</strong>:</p><ul><li><strong>supporters, per tenant.</strong> The people who <em>answer</em> in this group. Their messages return silent before the screen or the vision pass runs; the deployed function reports calls=0 on that path. An explicit call to the bot is exempt, because a supporter may address it on purpose.</li><li><strong>quoted_participant.</strong> The listener now passes the author of the quoted message. A reply inside a two-person exchange <strong>suppresses the question but not an answer</strong>: a ≥0.90 hit is worth having whoever it was aimed at; only the guess is unwelcome.</li><li><strong>A supporter-activity window.</strong> One row per <em>group</em>, because “is a human already on this?” is a property of the room. 180 seconds, the observed gap between a question and one of the group’s own answerers picking it up.</li></ul><p>And one number that changed a default. Route 2, the clarifying question when the classifier finds <em>nothing</em> and the screen says the message is too vague, is a bet that the KB can answer once the message is sharpened. Measured in the second group over its first week, against an 8-entry knowledge base: <strong>11 clarifying questions, 0 answers.</strong> Every follow-up ended in silence because no answer existed to be found. The people who replied got nothing for replying. Route 2 is now a per-tenant flag: off for the small KB, on for the 41-entry one where the same trade was measured to pay. With a small KB the bet always loses, and the bot spends its credibility asking questions it cannot use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zanruCBvSIQ0iPoeDUb5CQ.png" /></figure><p><em>From the demo: a screenshot is read by the vision model and answered from the same knowledge base.</em></p><h3>4. Trigger order is load-bearing</h3><p>This one cost me a correct answer three separate times before I drew the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNde4EKBm4Y-p0MQCRfqBg.png" /></figure><p><em>Figure 4. The classifier is shown the first six phrasings of each entry. Position 8 does not exist as far as it knows.</em></p><p>To keep the catalogue cacheable and the cost flat, each entry contributes its <strong>first six</strong> trigger phrasings to the prompt. A real question about extending a security token scored 0.85 against the right entry and got a clarifying question instead of the answer. The entry contained the exact phrase the user typed, at trigger <strong>#8</strong>. Moving it to #5, same set, positions only, took the score to 0.92, three runs out of three.</p><p>The regression gate caught it, not review. The lesson generalises: when you truncate a list to bound a prompt, the truncation is a product decision, and the tool that edits the list has to know about it. My KB checker now warns at position 7 or later, and the curator in section 6 may only add phrasings at positions ≤ 6.</p><h3>5. Two groups, one bot, and then 1:1</h3><p>When the second division asked for a bot, the obvious move was a second number: a second SIM, session, EC2 and linking ceremony, for nothing the users would see. Instead a <strong>tenant</strong> is a folder, tenants/&lt;id&gt;/, with a tenant.json (group ids, table, disclosure header, prompt audience text, the supporters list, the route-2 flag) and a kb.json. The brain resolves the tenant from the group id on every message. Shared: the account, the listener, the code, the floors. Per tenant: the KB, the texts, the policy flags. The first tenant&#39;s measured behaviour is pinned by tests, so adding a second cannot move it.</p><p>Then people started messaging the bot privately. Three had already tried, one with a screenshot, and been dropped in silence because the listener only accepted group messages. So: the same engine, reached directly, with three deltas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhvSLMqibvoXGqbcgXEa-A.png" /></figure><p><em>Figure 5. The disambiguation design exists for four people.</em></p><p><strong>Authorisation is a live roster, not a list.</strong> Every 15 minutes the listener rebuilds “who is in which pilot” from the groups’ own membership, so someone removed from a group loses DM access at the next refresh with nobody maintaining a second list. A roster that builds <em>empty</em> is refused, because an empty map denies everybody and looks exactly like the feature being broken.</p><p><strong>A stranger gets silence, never a refusal.</strong> “You are not authorised” would confirm to whoever is probing that this number is a support bot for a specific organisation. That is not theirs to learn.</p><p><strong>The tenant comes from the roster too.</strong> Measured on the live groups: <strong>215 people</strong>, 119 in one pilot only, 91 in the other only, <strong>4 in both</strong>. So 98% of people are never asked anything. The four are asked once, “which pilot?”, and the answer is remembered for 90 days. I nearly built per-message inference for this; the numbers said one remembered answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekD00sw3bxRfqSPTpiAnew.png" /></figure><p><em>From the demo: the one-time “which team?” question, then a normal answer.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5sl90Ad4fiQqMnoBU26bQ.png" /></figure><p><em>From the demo: in a private chat a no-match says so.</em></p><p><strong>A DM is treated as explicit.</strong> Silence is a designed, readable answer in a 120-person group. In a private chat it is a bot ignoring you. So a DM carries the weight an @-mention already carries: the screen is skipped, and a no-match says so in a fixed sentence. The group-only suppressions from section 3 are all guarded on “not explicit”, so they switch themselves off in a DM without a second flag. A supporter asking the bot privately is a person with a question.</p><p>The whole channel sits behind one environment variable, default off, because a private channel where 200 staff send screenshots is a different data-flow story from a bot in a group, and that story belongs in front of a security reviewer before the flag goes to 1.</p><h3>6. The curator: learning from the log without writing</h3><p>Feeding the knowledge base was me reading the group, finding the question a human answered and someone confirmed, writing the entry, ordering the triggers, running the checker, publishing. Two sessions a week of that is not a process. The second division’s KB owner had the right expectation: when there is high-confidence new knowledge in the group, the KB should reflect it without a person having to notice.</p><p>My constraint: a different layer, integrated in no way that could jeopardise the running bot. That ruled out the brain writing events anywhere and pointed at something better: everything the curator needs is already in bot.log. It <em>pulls</em> the log, a read the bot cannot tell happened, and nothing on the operational path changed. A bug in the curator cannot reach a group, by construction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDTLJf8iUqZNrKEktXVZMw.png" /></figure><p><em>Figure 6. Only Tier A touches the KB without a click, and only where the answer text cannot change.</em></p><p>The log carries every verdict but not the fact most useful for fixing a KB: on a miss, which entry the bot <em>nearly</em> picked. The curator recovers it by re-classifying every miss offline through the same brain module, one cheap call per miss. Then three tiers. <strong>Tier A, applied</strong>: a phrasing added to an <em>existing</em> entry, at position ≤ 6. <strong>Tier B, draft</strong>: a <em>new</em> entry with status=draft, which the KB owner publishes in the console they already use. <strong>Tier C, reported</strong>: repeated gaps, review flags and unanswered questions, in a digest to a human.</p><p><strong>The day-one lesson: matching is not correctness.</strong> Tier A’s first gate was “re-classifying the missed message against the modified entry clears 0.90.” That proves a phrasing makes the entry <em>match</em>. It says nothing about whether the match is <em>right</em>. In the dry run the curator was about to teach the sign-in entry the phrasing “can’t log in to Outlook”, lifted from a thread that had actually resolved a drag-and-drop problem. The bot would then have given the sign-in answer, confidently, to every generic login complaint.</p><p>Worse, when I asked the model whether the thread confirmed the entry, it rationalised a confirmation that was not there. So the gate is now a separate, narrow judgement over the thread, <em>did a human give this entry’s answer, and did the asker accept it?</em>, whose output is checked in code alongside the KB checker (a change may not <em>add</em> a warning), a duplicate check, and a rule that an id is never overwritten. In the live run it refused exactly that case, twice.</p><p><strong>Where a rule can be checked in code, check it in code.</strong> The model is good at “does this thread look like a confirmation?” and bad at also deciding whether to act on it. Split the two.</p><p>Proven end to end in test groups: a phrasing the bot had only clarified at 09:11 was answered at 09:25 after Tier A wrote it (then reverted, because one person confirming in a test group is not evidence), and a seeded thread became a draft that was silent while draft, answered once published, silent again once deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r78zy8zEBZhlD4Nf0DTwOQ.png" /></figure><p><em>A digest produced by the template’s curator on its bundled example log — the real ones name internal entries, so they stay out of the article.</em></p><h3>7. The 60-second stall that looked like silence</h3><p>While seeding those threads, a “got it, thanks!” message produced a Lambda <strong>timeout at 60,000 ms</strong>. The listener printed outcome=undefined and moved on, which in a group reads as the bot correctly staying quiet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBZOyXaASGHogpLRkS02sw.png" /></figure><p><em>Figure 7. The two defaults are equal, so one stalled call consumes the whole budget and fails invisibly.</em></p><p>botocore’s default read timeout is 60 seconds. My Lambda’s timeout was 60 seconds. One stalled model call ate the entire budget and surfaced as an absence. The client is now bounded (connect 5 s, read 25 s, two attempts), a stall fails fast into the existing fail-silent paths, and the listener prints BRAIN ERROR so a human, and the curator, can see it. If you run a model call inside a Lambda, check that the SDK&#39;s read timeout is shorter than the function&#39;s. The defaults are set so that it is not.</p><h3>8. Costs, risks, what is next</h3><h3>What it costs</h3><ul><li><strong>EC2 t3.small, always on</strong>: ~$15</li><li><strong>16 GB gp3</strong>: ~$1.50</li><li><strong>Lambda, DynamoDB, CloudWatch</strong>: rounds to $0 at support-group volume</li><li><strong>Model calls, per message</strong>: $0.0013 when the screen drops it; ~$0.0024 when classified, with prompt caching</li></ul><p>Call it $18 a month plus a few cents a day. The catalogue sits at the end of a stable system prompt with nothing per-request before it, so Bedrock’s prompt cache takes two thirds off the classify call once the KB passes about 25 entries. Set a budget alert before apply.</p><h3>What could go wrong</h3><ul><li><strong>The number gets banned.</strong> Dedicated SIM, reply-only, human pacing. A real risk I will not quantify, because nobody outside Meta can.</li><li><strong>The phone goes offline for 14 days.</strong> WhatsApp unlinks devices. The listener notices and shows a new QR. Keep the phone plugged in.</li><li><strong>Messages sent while the listener is down are gone.</strong> WhatsApp does not replay them to a linked device. Check the ready timestamp before believing the bot ignored something.</li><li><strong>WhatsApp delivers a message twice.</strong> It happened in the real group: one screenshot, two identical 1,600-character answers to 122 people, because the listener had no duplicate check. It does now.</li><li><strong>The KB decays silently.</strong> The bot once gave a stale version number with total confidence. Every entry carries last_verified and what it was verified against, and Tier C flags entries whose measurements are undated.</li></ul><h3>What is next</h3><p>The curator runs three times a day from a workstation; it belongs on a cloud schedule, with the digest sent as a DM from the bot. Per-user memory for 1:1 (“this person is on macOS, version X”) would raise match quality, with one hard rule: memory may feed <em>matching</em> and the clarifying question, never the answer text, or the bot starts writing. And supporters is the one field that goes stale on its own; a stale entry costs a silence, never a wrong answer, but it is invisible, so re-check it when the bench changes.</p><h3>9. Build one: the knowledge base is the work</h3><p>Everything above is design. Here is the part you can copy. It takes an afternoon, and almost all of that afternoon goes into the knowledge base rather than the code.</p><h4>Step 1. Write ten entries before you deploy anything</h4><p>An entry is a JSON object. This is a real one from the template, trimmed:</p><pre>{<br>  &quot;id&quot;: &quot;vpn_not_connecting&quot;,<br>  &quot;category&quot;: &quot;network&quot;,<br>  &quot;status&quot;: &quot;published&quot;,<br>  &quot;triggers&quot;: [<br>    &quot;vpn won&#39;t connect&quot;,<br>    &quot;vpn keeps disconnecting&quot;,<br>    &quot;vpn stuck on connecting&quot;,<br>    &quot;can&#39;t reach internal sites from home&quot;<br>  ],<br>  &quot;error_strings&quot;: [<br>    &quot;The VPN connection failed due to unsuccessful domain name resolution&quot;<br>  ],<br>  &quot;answer&quot;: &quot;VPN will not connect, or keeps dropping. Checklist, in this order:\n1. Quit the VPN client completely, then reopen it. Disconnect alone is not enough.\n2. Make sure the profile is *Corp-Remote*, not *Corp-Guest*...&quot;,<br>  &quot;owner&quot;: &quot;network on-call&quot;,<br>  &quot;last_verified&quot;: &quot;2026-09-15&quot;,<br>  &quot;verified_against&quot;: &quot;Thread 2026-09-02 09:14-09:31: asker reported the DNS error on a hotel network; on-call answered; asker replied &#39;restart did it, connected&#39;.&quot;<br>}</pre><p>Four fields do the work, and it is worth knowing which is which.</p><p><strong>triggers</strong> is the only thing the model matches against. Write the phrasings your people actually type, not the phrasing you would use in a ticket. Mine are a mix of English and Hebrew because my group types both, often in the same sentence. Only the first six are ever shown to the classifier, so the sixth slot is the last one that exists.</p><p><strong>error_strings</strong> are exact on-screen strings. These are the highest-signal thing in an entry, because a person pasting an error message is quoting the software verbatim. If you have one, use it.</p><p><strong>answer</strong> is what the group receives, character for character. Write it as a numbered checklist in the order you would actually try things, and say what <em>not</em> to do where people get it wrong. No greeting, no sign-off, no “I hope this helps” — it is going into a busy group, not an email.</p><p><strong>verified_against</strong> is the field that keeps the whole thing honest. It quotes who said what and when the answer was last known to work. Stale entries, not wrong matching, are the failure mode you will actually hit six months in.</p><p>Ten entries is enough to start. Twenty covers most of what repeats.</p><h4>Step 2. Check the KB before it reaches anyone</h4><pre>KB_TENANT=dev-platform python3 kb/kbcheck.py --warnings</pre><p>The checker enforces the rules that cost real answers: a trigger sitting past position six where the classifier cannot see it, a duplicate id, a missing verification date, and the WhatsApp formatting traps — *bold* renders only when the asterisk starts a word, so a Hebrew one-letter prefix glued to it prints the asterisks instead. It refuses to publish on an error.</p><h4>Step 3. Stand up the infrastructure</h4><pre>cd infra/terraform<br>terraform init &amp;&amp; terraform apply<br>KB_TENANT=dev-platform python3 kb/publish.py</pre><p>That creates a VPC with no inbound ports, a t3.small for the listener, the brain Lambda, one DynamoDB table per group and one for conversation state, and the IAM to bind them. There is a CloudFormation template if you prefer one file. Set a budget alert first: the steady cost is the instance, about $15 a month, and everything else rounds to pennies.</p><h4>Step 4. Test the brain before WhatsApp exists at all</h4><p>This is the step people skip, and it is the one that saves the embarrassment. The brain is a Lambda that takes text and returns a verdict, so you can interrogate it directly:</p><pre>scripts/ask.sh &quot;vpn keeps dropping when I work from home&quot;<br>python3 tools/probe.py --tenant dev-platform</pre><p>You get back the entry it chose, the confidence, and the outcome — answer, clarify or silent. Feed it a week of your group’s real messages before it has met anyone, and grade the confident answers by hand. That exercise is how I learned my 0.85 bucket was 92% wrong or partial, which is why the production bot runs at 0.90. Pick your floor from your own data, not from mine.</p><h4>Step 5. Link the phone, in a room with nobody in it</h4><p>Buy a prepaid SIM and put it in an old Android. Never your own number: if it gets banned you lose that SIM, and if it were your number you would lose your chats, your groups and your family with no appeal that works.</p><pre>scripts/qr.sh     # opens the QR page over an SSM tunnel</pre><p>Scan it from WhatsApp under Linked devices, then put the bot in a group containing you and the bot and nobody else. Ask it the ten questions you wrote. Read every reply. Fix the entries that matched badly, and the ones that matched nothing.</p><p>Only then add it to a group with people in it.</p><h3>10. What I would do differently</h3><p><strong>Pass the whole message shape from day one.</strong> Sender role, quoted author, whether the bot was addressed. I spent two weeks tuning a rule the model could never apply because the fact was not in the input. Structure first, prompt second.</p><p><strong>Measure before choosing the floor.</strong> The 0.80 floor was a guess. The replay with an independent judge took an afternoon and moved the wrong-answer rate from 42% to 6%. Have that afternoon before the bot meets real people.</p><p><strong>Treat every truncation as a product rule.</strong> “First six triggers” was a cost optimisation in one function. It became the reason three correct answers were withheld. If a limit changes behaviour, the editing tool must enforce it and the tests must know it.</p><p><strong>Start the second group as a tenant, not a fork.</strong> The tenant model took a day and made every later feature, DMs and the curator, land for both groups at once.</p><p><strong>Put gates in code from the first prototype of anything that writes.</strong> The curator’s model judgement rationalised a confirmation on its first run. Not maliciously, not unusually; that is what a model does when the question is “should I act?”. Ask it narrow questions and let code decide.</p><p><strong>Test where the user looks.</strong> Invoking the Lambda proved the code. Only sending a message in the group, editing the entry, sending the same question worded differently and watching the reply change proved the bot. The duplicate delivery and the 60-second stall were both invisible one hop below the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*WFvta-ri2PEq28C19GbFOg.png" /></figure><p><em>The tests are the design rules, named.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Qowjg3WMp5K8mf_-VuryCQ.png" /></figure><p><em>The KB checker enforces the two rules that cost real answers.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*aaqGa9k2ZMTICTDuzxLvig.png" /></figure><p><em>A real Bedrock run against the template’s example KB, from the repo’s </em><em>tools/probe.py.</em></p><h3>Try it yourself</h3><p>The repo is <a href="https://github.com/kobyal/whatsapp-kb-bot">github.com/kobyal/whatsapp-kb-bot</a>: Terraform and CloudFormation, the listener, the brain with the three-outcome pipeline and conversation awareness, tenants/ for multi-group, the 1:1 mode behind its flag, the KB checker, the curator/ layer, and the design notes behind every number here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*he2Ejbugtd5w6nUMtAIh2g.png" /></figure><p><em>One build script, two IaC flavours, both validated.</em></p><p>Start smaller than this article makes it sound. One group, one knowledge base, twenty entries. Leave 1:1 chats off and leave the curator off: both exist because the bot outgrew a single group, and neither helps on day one. Run it for a fortnight and read every answer it gives. Turn on private chats when people start asking you things the group already answered, and turn on the curator when you are tired of adding entries by hand. A bot that answers twenty questions well beats one with every feature enabled and a knowledge base nobody trusts.</p><ol><li>Fork it. Replace the sample kb.json with your team&#39;s twenty questions. Put the phrasings people actually use in the first six triggers.</li><li>terraform apply, publish the KB, and call the brain directly with scripts/ask.sh until the answers and the silences both look right.</li><li>Get a dedicated SIM and an old phone. Scan the QR. Start in a private test group with you and the bot.</li><li>Replay a week of your real group’s messages before it meets anyone. Grade the confident answers. Then pick the floor.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*R7sEcCtBh5aMB2lBXmbPvQ.png" /></figure><p>The listener serves this QR page over an SSM tunnel — no SSH, no open ports. The code lives about twenty seconds, so the page refreshes itself while you go and fetch the phone.</p><p>If you would rather not run an unofficial client, the brain works unchanged behind the official Cloud API for 1:1 support. Only the listener changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmfjJ3XZwx3z96zBFP4IkQ.png" /></figure><p>One last thing. The most valuable line of code in this project is the one that decides to say nothing. If you build one of these, spend your first week on that decision, not on the answers.</p><p><em>Koby Almog is an AI tech lead in Israel and writes about making AI tools useful in regulated environments. Personal project; opinions his own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=057456740dfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Turned 47 AWS Summit Talks Into PDFs — A 4-Stage Open-Source Pipeline]]></title>
            <link>https://medium.com/@kobyal/how-i-turned-47-aws-summit-talks-into-pdfs-a-4-stage-open-source-pipeline-0aeb2fa34ace?source=rss-38b993992beb------2</link>
            <guid isPermaLink="false">https://medium.com/p/0aeb2fa34ace</guid>
            <dc:creator><![CDATA[Koby Almog]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 05:40:18 GMT</pubDate>
            <atom:updated>2026-09-17T05:40:18.502Z</atom:updated>
            <content:encoded><![CDATA[<p>Pull the slides out of the recording, transcribe locally, and render a typeset document. Running it across an entire conference is what found the real bugs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UM4o0tQDu0j_pcYHFEtiSA.gif" /></figure><h3>Introduction</h3><p>Last week I attended <strong>AWS Summit Tel Aviv 2026</strong> — 14,000 people, 90+ sessions, and a schedule that forces you to choose. I picked five talks about <strong>running AI agents in production</strong>, enjoyed every one of them, and came home with a head full of ideas and a camera roll full of slide photos taken from row fifteen.</p><p>A week later I noticed something uncomfortable: I couldn’t reconstruct most of what I’d heard. Not the talks I skipped — <strong>the ones I actually sat through</strong>.</p><p>Then AWS started publishing the recordings (48 of 90+ so far, at <strong>summittelaviv.awslivestream.com</strong>). That should have solved it, and it didn’t, because <strong>video is a terrible format for going back to something</strong>. You can’t scan it, you can’t search inside it, and you can’t send it to your team and expect anyone to spend 40 minutes. The information is in there, locked behind a play button and a linear timeline.</p><p>What I wanted was a <strong>document</strong> — something I could skim in five minutes, search next month, and hand to a colleague. So I built one, open-sourced it, and then ran it across the entire conference, which is where it got interesting.</p><p>This guide covers <strong>how the pipeline works stage by stage</strong>, the four bugs that only appeared at scale, <strong>why Hebrew in Word is three separate bugs</strong>, and how to run it yourself. We’ll cover:</p><ul><li><strong>Fetching</strong> recordings from YouTube, auth-gated Zoom, and conference streaming platforms</li><li><strong>Local transcription</strong> with Whisper — nothing uploaded, nothing billed</li><li><strong>Extracting the speaker’s slides</strong> out of the video with scene detection</li><li><strong>Rendering</strong> a typeset DOCX and PDF with the slides interleaved</li></ul><p>Code: <strong>github.com/kobyal/recording-to-pdf</strong> (MIT)</p><p>This isn’t just theory — <strong>this is the pipeline that produced 47 documents and 781 pages in one overnight run</strong>.</p><h3>What This Pipeline Does</h3><p>You give it a link to a recording. It gives back a typeset PDF with the speaker’s own slides placed inside the argument, and <strong>every quote carrying a timestamp</strong> back to the source.</p><p>The flow: <strong>Fetch → Transcribe → Slides → Render</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yh-HBb0x1JP_dFV7V0wdMA.png" /><figcaption>three pages from one 25-minute session — exec summary, the demo walkthrough, the architecture slide</figcaption></figure><p>Each document runs <strong>14 to 19 pages</strong>, opens with an executive summary, follows the talk’s own running order, and puts the relevant slide beside the argument it belongs to.</p><h3>Step-by-Step Guide: Building the Pipeline</h3><h3>Step 1: Fetch the recording</h3><pre>bin/r2r fetch &quot;https://www.youtube.com/watch?v=...&quot; work/</pre><p><strong>YouTube</strong> works directly. <strong>Zoom</strong> recordings need --cookies-from-browser chrome — without it yt-dlp reports “no video formats found”, which looks like a format problem and is actually <strong>authentication</strong>.</p><p>The <strong>conference streaming platform</strong> was the interesting one. The session pages are gated behind a login, but the video manifests underneath are not. The resolver walks from the event site → its CMS config → the encoded output, so you can point it at a session URL and it just works.</p><p><strong>Note:</strong> these HLS masters carry <strong>video-only renditions plus a separate audio group</strong>. My first download produced a file that transcribed to complete silence. Map both explicitly:</p><pre>ffmpeg -i &lt;video_variant&gt; -i &lt;audio_variant&gt; \<br>       -map 0:v:0 -map 1:a:0 -c copy out.mp4</pre><h3>Step 2: Transcribe locally</h3><pre>bin/r2r asr work/ --lang he</pre><p>This runs <strong>mlx-whisper</strong> with <strong>large-v3-turbo</strong> on Apple Silicon — roughly <strong>12x faster than real time</strong>, so a 25-minute talk transcribes in about two minutes. <strong>Nothing uploads, nothing costs money</strong>, and after the first model download it works offline.</p><p>Two parameters matter, and I learned both the hard way on a 65-minute keynote:</p><ul><li><strong>Always set the language explicitly</strong> — I let it auto-detect once, the pre-show noise made it decide a Hebrew keynote was English, and it returned a page of “Thank you.” repeated.</li><li><strong>Turn off </strong><strong>condition_on_previous_text</strong> — otherwise the model feeds its own output back as context and loops on repeated phrases during silence.</li></ul><p>Whisper returns segments of a few seconds each, which no human can read. Collapsing them into <strong>~90-second timestamped blocks</strong> gives you the form you actually work from:</p><pre>[11:11] The orchestrator receives the transaction and does planning...</pre><p>Those timestamps become <strong>the citations in the final document</strong> — every quote can be checked against the recording in seconds, which matters when the source is machine-transcribed.</p><h3>Step 3: Pull the slides out of the video</h3><p>This is the stage that earns the whole project.</p><p>A recording <strong>already contains the deck at full resolution</strong>, one frame at a time. You don’t need the speaker to send you the PDF, and you certainly don’t need photographs from row fifteen. Scene detection pulls one frame per slide in a single decode pass:</p><pre>ffmpeg -i rec.mp4 -vf &quot;select=&#39;gt(scene,0.12)&#39;,showinfo,scale=1400:-1&quot; \<br>       -vsync vfr -q:v 2 frames/s_%04d.jpg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CAfwndVjqW6cRiMhyoiY4w.png" /><figcaption>one 25-minute talk — 90 frames detected, 55 unique after dedupe, 40 seconds total</figcaption></figure><p><strong>Threshold 0.12</strong> was right here — lower gives duplicates, higher misses slides. A perceptual hash drops the near-duplicates. And <strong>don’t pass </strong><strong>-v error</strong> if you want the frame timestamps, it suppresses showinfo.</p><p>Then the complication specific to conference recordings: <strong>the production mix doesn’t show you a clean deck</strong>. It shows a camera pointed at a stage, with the slide inset among lights, speakers and branded panels. Drop those into a document and it looks like a holiday album.</p><p>So there’s a crop step that finds the largest screen-shaped rectangle in the frame and trims to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-i9PSw7LtAHQEQNMwawnzA.png" /><figcaption>same frame, before and after. the cropper wants roughly 16:9, big enough, with visible edges</figcaption></figure><p>Frames where it finds nothing convincing <strong>pass through untouched</strong> — deliberate, because an earlier version silently dropped them and the slide set came out with holes in it.</p><h3>Step 4: Render the document</h3><pre>bin/r2r render work/ --content content.json --name MyTalk</pre><p>The document is <strong>data</strong>. You write a content.json and the renderer produces a <strong>DOCX, then converts it to PDF</strong>, so you get both — and anyone who wants to edit gets a real Word file:</p><pre>{&quot;kind&quot;: &quot;h1&quot;,      &quot;text&quot;: &quot;1. Executive summary&quot;},<br>{&quot;kind&quot;: &quot;bullets&quot;, &quot;items&quot;: [[&quot;The claim: &quot;, &quot;the evidence&quot;]]},<br>{&quot;kind&quot;: &quot;image&quot;,   &quot;file&quot;: &quot;k_012.jpg&quot;, &quot;caption&quot;: &quot;...&quot;},<br>{&quot;kind&quot;: &quot;callout&quot;, &quot;text&quot;: &quot;...&quot;, &quot;label&quot;: &quot;Note&quot;}</pre><p><strong>The pipeline deliberately stops before the writing.</strong> Choosing which slides matter and turning a transcript into an argument is judgement work, and a tool that pretends otherwise produces confident garbage. In my own use a language model writes the content.json from the transcript and the contact sheets and I review it — but nothing in the pipeline requires that.</p><h3>Running It on an Entire Conference</h3><p>I could have shipped after one talk. Instead I pointed it at <strong>all 48 published sessions</strong>: about four hours of unattended processing, 957 MB of source, <strong>47 documents and 781 pages</strong> out the other end. One session had no recording at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdNMFbVJx0sILOUdU_y6bw.png" /><figcaption>the generated index — every session, grouped by track, with page counts</figcaption></figure><p>Every bug below came out of that run. <strong>None of them was visible on a single happy-path talk.</strong></p><h3>🛠️ Common Issues &amp; Troubleshooting</h3><h3>❌ Issue 1: The transcript is completely empty</h3><p><strong>Possible Cause:</strong> The downloaded file has <strong>no audio track</strong>. HLS masters often carry video-only renditions with audio as a separate group, and a naive download grabs only the video.</p><p><strong>Fix:</strong> Mux both explicitly with -map 0:v:0 -map 1:a:0. <strong>How to check:</strong> run ffprobe and confirm an audio stream exists before transcribing.</p><h3>❌ Issue 2: The download hangs forever with no error</h3><p><strong>Possible Cause:</strong> An <strong>HLS segment fetch stalled</strong>. One of mine sat at <strong>1% CPU</strong> on a file that had stopped growing 20 minutes earlier. No error, no exit — ffmpeg simply waits.</p><p><strong>Fix:</strong> Add reconnect flags (-reconnect 1 -reconnect_streamed 1 -rw_timeout), a <strong>wall-clock timeout</strong>, and a retry that treats a hang as failure. Also verify the result with ffprobe — <strong>ffmpeg will happily exit 0 on a truncated stream</strong>.</p><h3>❌ Issue 3: 48 videos don’t fit on your laptop</h3><p><strong>Possible Cause:</strong> Downloading <strong>1080p out of habit</strong>.</p><p><strong>Fix:</strong> Slide text is just as legible at <strong>720p</strong>, which halves both download time and disk. The batch runner also <strong>deletes each video once the frames are extracted</strong>, keeping peak disk around 1 GB for a whole conference.</p><h3>❌ Issue 4: A talk that was never published produces a document anyway</h3><p>This is the one worth your time.</p><p><strong>Possible Cause:</strong> Sessions the event never published <strong>still list preshow “slate” loops</strong> in their configuration — the placeholder video a stream plays before it starts. My resolver downloaded one, transcribed silence, and found no slides.</p><p><strong>Fix:</strong> Only accept a <strong>real encoded output</strong> as a recording; anything else is marked <em>skipped</em> in three seconds.</p><p><strong>Why this matters more than the others:</strong> the failure I saw was a crash. The <strong>near miss</strong> was much worse — a slightly different code path would have produced a confident, well-typeset, <strong>entirely empty document from placeholder footage</strong>, and nothing in the output would have looked wrong. That is the failure mode of every summarising tool: it doesn’t error, it produces something plausible. That bug alone justified running the whole set instead of a sample.</p><h3>Hebrew in Word: Three Separate Bugs, and LibreOffice Hides All of Them</h3><p>This was <strong>the single largest time sink in the project</strong> — not the transcription, not the scene detection. Right-to-left text in OOXML.</p><ul><li><strong>Element order:</strong> w:bidi must sit in its schema position inside the paragraph properties, <strong>before</strong> spacing and justification. Appended at the end, Word silently ignores it and the paragraph falls back to left-to-right.</li><li><strong>Complex-script properties:</strong> Hebrew is a complex script, so Word reads <strong>w:szCs and </strong><strong>w:bCs</strong>, not w:sz and w:b. Set only the latter and Hebrew renders at the wrong size and unbolded, right next to correctly sized Latin text.</li><li><strong>Justification is logical, not physical:</strong> inside a bidirectional paragraph, w:jc set to right means the <strong>trailing</strong> edge — which in RTL is the visual <strong>left</strong>. Explicitly right-aligning Hebrew flushes it the wrong way. Emit <strong>no</strong> justification and let the bidi flag do the work.</li></ul><p><strong>Note:</strong> LibreOffice forgives all three. Your document previews perfectly, you ship it, and someone opens it in Word or Pages and it’s broken. <strong>Verify against the XML or against Word itself — never against a LibreOffice preview.</strong></p><h3>Best Practices</h3><ul><li><strong>Run it on more than one talk before you trust it.</strong> Every bug above was invisible on a single happy-path run. Four of them turned up in one overnight batch of 48.</li><li><strong>Let each stage degrade instead of failing.</strong> Scene detection keeps the frames it already wrote. The cropper passes through what it can’t crop. A download is only accepted once ffprobe confirms a video stream and a real duration, because ffmpeg will exit 0 on a truncated file.</li><li><strong>Check one frame before processing an hour of video.</strong> A talking-head recording with no screen share gives you nothing, and you’d rather learn that in ten seconds.</li><li><strong>Budget for the writing, not the processing.</strong> Four minutes of compute per talk. The summary is the part that takes real time.</li></ul><h3>✅ Closing Thoughts</h3><p>47 documents, 781 pages, one overnight run. The pipeline did the mechanical work; I still read and edited every summary that came out of it.</p><p>The bug that stayed with me is the placeholder one — not because it was hard to fix, but because of how it would have failed. A summarising tool doesn’t crash when it’s wrong. It hands you something that looks finished.</p><p>If you try it, start with a talk you already know well. You’ll see immediately whether the slide selection and the quotes are any good, and that’s the only test that matters.</p><p>One last thing. All of this exists because the slides had to be recovered from video, frame by frame, to reconstruct a PDF that already sits on someone’s laptop. If you run an event and publish the recordings — publish the decks too.</p><h3>📚 Resources</h3><ul><li><strong>recording-to-pdf on GitHub</strong> — github.com/kobyal/recording-to-pdf</li><li><strong>AWS Summit Tel Aviv 2026 recordings</strong> — summittelaviv.awslivestream.com</li><li><strong>mlx-whisper</strong> — Whisper on Apple Silicon</li><li><strong>yt-dlp</strong> — the fetch layer for YouTube and Zoom</li><li><strong>Example output</strong> — a 25-minute session as a 14-page Hebrew document, in the repo under examples/</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0aeb2fa34ace" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Replaced My Morning AI News Routine With Google ADK — A 6-Step Multi-Agent Pipeline]]></title>
            <link>https://medium.com/@kobyal/how-i-replaced-my-morning-ai-news-routine-with-google-adk-a-6-step-multi-agent-pipeline-cb38bc857582?source=rss-38b993992beb------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb38bc857582</guid>
            <dc:creator><![CDATA[Koby Almog]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 06:51:52 GMT</pubDate>
            <atom:updated>2026-03-23T06:51:52.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mvTdHmmwglPyNveWOhojag.png" /></figure><p>Every morning I’d open a handful of tabs — vendor blogs, X, Reddit, Hacker News, a couple of newsletters — trying to piece together what actually happened in AI the past few days. New Claude model? AWS Bedrock announcement? OpenAI dropped something? Half the time I’d miss it entirely. The other half I’d spend 20 minutes and still not feel confident I had the full picture.</p><p>So I built an agent that does it for me. It searches across 5 major AI vendors (Anthropic, AWS, OpenAI, Google, Azure — configurable to whatever you care about), finds what developers are actually saying on HN and Reddit, and drops a clean bilingual HTML newsletter in my browser. Done.</p><p>Here’s exactly how I built it with <strong>Google ADK</strong> — and what I learned the hard way. This isn’t a “look what AI can do” demo. It’s a real build log: the architecture decisions, the caveats you’ll hit, and the patterns that actually work.</p><p><strong>Code</strong>: <a href="https://github.com/kobyal/ai-latest-briefing">github.com/kobyal/ai-latest-briefing</a></p><h3>What We’re Building</h3><p>A <strong>6-step autonomous pipeline</strong> that:</p><ol><li>Searches for the latest news (last 3 days) from Anthropic, AWS, OpenAI, Google, and Azure</li><li>Resolves all source URLs <em>immediately</em> while grounding redirects are still fresh</li><li>Finds what developers on HN and Reddit are actually saying</li><li>Structures everything into a clean, dated briefing with verified source links per story</li><li>Translates the entire briefing to Hebrew</li><li>Saves a self-contained HTML newsletter with an EN/עברית toggle</li></ol><p>The output: a dark-header newsletter with a TL;DR, color-coded vendor cards, publication dates, 2–3 working source links per story, community reactions, and a language toggle. Opens instantly in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*px3kG2lLmBNUE99eRCKf1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iT1DJlgDqNSBfo9Poe_iTQ.png" /></figure><h3>What is Google ADK?</h3><p><strong>ADK (Agent Development Kit)</strong> is Google’s open-source framework for building multi-agent AI systems. Think of it as the plumbing between your LLM calls — it handles session state, tool execution, agent orchestration, and ships with a built-in web UI for debugging.</p><p>You define agents as Python objects. You chain them. ADK handles the rest.</p><p>Three building blocks do all the work.</p><h3>LlmAgent — one agent, one job</h3><pre>from google.adk.agents import LlmAgent<br>from google.adk.tools import google_search<br><br>researcher = LlmAgent(<br>    name=&quot;VendorResearcher&quot;,<br>    model=&quot;gemini-2.5-flash&quot;,<br>    tools=[google_search],        # tools this agent can call<br>    output_key=&quot;raw_vendor_news&quot;, # saves response to session state<br>    instruction=&quot;Search for the latest AI news...&quot;,<br>)</pre><p>LlmAgent is the workhorse. Key parameters:</p><ul><li><strong>model</strong> — gemini-2.5-flash is fast and cheap; gemini-2.5-pro when you need deeper reasoning.</li><li><strong>tools</strong> — built-in tools like google_search, or plain Python functions.</li><li><strong>output_key</strong> — ADK automatically saves the agent&#39;s final response into session state under this key. Downstream agents can read it instantly.</li><li><strong>output_schema</strong> — pass a Pydantic model and ADK forces the response to be valid JSON matching that shape. <strong>The most underrated feature in the whole framework.</strong> More on this in Step 4.</li><li><strong>instruction</strong> — the system prompt. Reference session state values with {{state.key}} — ADK substitutes the real value at runtime.</li></ul><h3>SequentialAgent — chain agents in order</h3><pre>from google.adk.agents import SequentialAgent<br><br>root_agent = SequentialAgent(<br>    name=&quot;AILatestBriefing&quot;,<br>    sub_agents=[<br>        VendorResearcher,    # runs first<br>        URLResolver,         # runs second, reads state from step 1<br>        CommunityResearcher, # runs third<br>        BriefingWriter,      # runs fourth<br>        Translator,          # runs fifth<br>        Publisher,           # runs last<br>    ],<br>)</pre><p>SequentialAgent runs sub-agents one at a time, in order. Each agent&#39;s output flows into shared session state. The next agent&#39;s instruction template can reference it via {{state.key}}.</p><p>No manual wiring. No callbacks. No message passing. <strong>State is the communication channel.</strong></p><h3>Session State — the shared memory</h3><p>When an agent has output_key=&quot;raw_vendor_news&quot;, its final response text is stored as state[&quot;raw_vendor_news&quot;]. Any downstream agent can reference it:</p><pre>Here is the vendor news gathered so far:<br>{{state.raw_vendor_news}}</pre><p>ADK substitutes the real value before sending the prompt to the model. This is how 6 agents share context without you writing a single line of plumbing.</p><h3>The Constraint That Forces Good Design</h3><p>Before diving into the pipeline, you need to know this:</p><p><strong>Gemini cannot use built-in tools (like </strong><strong>google_search) and custom Python function tools in the same agent.</strong></p><p>Try it and you get:</p><pre>400 Bad Request: Built-in tools and Function Calling cannot be combined</pre><p>This feels like a limitation at first. It’s not. It’s a design forcing function. An agent that searches shouldn’t also format HTML. An agent that resolves URLs shouldn’t also write copy. <strong>Single responsibility by default.</strong></p><p>In practice: if you need both search and a custom tool, split into two agents. You’ll thank yourself later when debugging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*6HstbLt3XcV2Fx7A-X4RvA.png" /></figure><h3>Building the Pipeline</h3><p>Here’s how each step is structured — and <em>why</em> it exists.</p><h3>Step 1 — VendorResearcher</h3><pre>VendorResearcher = LlmAgent(<br>    name=&quot;VendorResearcher&quot;,<br>    model=MODEL,<br>    tools=[google_search],<br>    output_key=&quot;raw_vendor_news&quot;,<br>    instruction=_fmt(VENDOR_RESEARCHER_PROMPT),<br>)</pre><p>The prompt runs 5 targeted searches (one per vendor) and outputs a structured text block with headlines, publication dates, summaries, and every URL it finds.</p><p>We inject the current date, month/year, and lookback window at module load:</p><pre>_today = datetime.now().strftime(&quot;%B %d, %Y&quot;)<br>_month_year = datetime.now().strftime(&quot;%B %Y&quot;)<br>_lookback_days = int(os.environ.get(&quot;LOOKBACK_DAYS&quot;, &quot;3&quot;))<br><br>def _fmt(template: str) -&gt; str:<br>    return (template<br>            .replace(&quot;{today}&quot;, _today)<br>            .replace(&quot;{month_year}&quot;, _month_year)<br>            .replace(&quot;{lookback_days}&quot;, str(_lookback_days)))</pre><p><strong>Why </strong><strong>LOOKBACK_DAYS?</strong> Without a freshness window, the model happily serves last week&#39;s stories as breaking news. The default is 3 days — a sweet spot that catches news that dropped over the weekend or during off-hours. Set to 1 for yesterday-only, 7 for a weekly digest.</p><p><strong>Why </strong><strong>{month_year} in search queries, not </strong><strong>{today}?</strong> My first prompts used queries like &quot;Anthropic Claude news March 22, 2026&quot;. On quiet days: zero results. Switching to &quot;Anthropic Claude latest news March 2026&quot; — broad month, no specific date — lets the search engine surface the most recent results naturally. Combined with &quot;prefer recent, don&#39;t hard-skip&quot; (the agent includes the latest available story even if outside the window, noting its actual date), all 5 vendors always produce something.</p><p><strong>URL hallucination caveat:</strong> When Gemini uses google_search, real article URLs appear in the grounding metadata as redirect links (vertexaisearch.cloud.google.com/...). When the model writes these into its text output, it sometimes misremembers or invents plausible-looking URLs that return 404. Never trust LLM-generated URLs without validation. That&#39;s what Step 2 is for.</p><h3>Step 2 — URLResolver</h3><p>This step exists entirely because of the URL problem above.</p><pre>URLResolver = LlmAgent(<br>    name=&quot;URLResolver&quot;,<br>    model=MODEL,<br>    tools=[resolve_source_urls],  # custom Python tool — no google_search!<br>    output_key=&quot;resolved_sources&quot;,<br>    instruction=URL_RESOLVER_PROMPT,<br>)</pre><p>The agent extracts every URL from {{state.raw_vendor_news}} and passes them all to resolve_source_urls in one call. The tool follows HTTP redirects, validates each URL returns 200, deduplicates, and filters junk (bare homepages, broken links, expired redirects).</p><p><strong>Why immediately after Step 1?</strong> This is the key insight. Grounding redirect URLs expire in ~30–60 seconds. If you resolve them at Step 5 or 6, most are already dead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*Zqn9SPzrv9dUyqvDP8curA.png" /></figure><p>Resolving in Step 2 — while the search session is still warm — consistently gets 10–16 working article URLs across all 5 vendors. That’s 2–3 sources per story.</p><p><strong>The Gemini constraint in action:</strong> resolve_source_urls is a custom Python function. That&#39;s why URLResolver cannot also have google_search. Two separate agents, two separate jobs.</p><p><strong>I tried adding a URLFinder agent first — it made things worse.</strong> My first instinct: add a dedicated step to run 10 additional targeted searches for more URLs, <em>then</em> resolve them. Result: the 60 seconds of extra searches was enough time for the original grounding redirects to expire. I was getting <em>fewer</em> working links with more steps. I removed it.</p><h3>Step 3 — CommunityResearcher</h3><pre>CommunityResearcher = LlmAgent(<br>    name=&quot;CommunityResearcher&quot;,<br>    model=MODEL,<br>    tools=[google_search],<br>    output_key=&quot;raw_community&quot;,<br>    instruction=_fmt(COMMUNITY_RESEARCHER_PROMPT),<br>)</pre><p>Reads the vendor news from state and searches Hacker News, Reddit/MachineLearning, and Reddit/LocalLLaMA for developer reactions to the top stories. Output is bullet-point reactions plus a COMMUNITY_SOURCES: block with direct links to the actual HN threads and Reddit posts.</p><h3>Step 4 — BriefingWriter</h3><pre>class NewsItem(BaseModel):<br>    vendor: str<br>    headline: str<br>    published_date: str   # &quot;March 22, 2026&quot; — exact date from source<br>    summary: str<br>    urls: List[str]       # from {{state.resolved_sources}} — pre-verified</pre><pre>class BriefingContent(BaseModel):<br>    tldr: List[str]            # exactly 3 cross-vendor highlights<br>    news_items: List[NewsItem]<br>    community_pulse: str<br>    community_urls: List[str]</pre><pre>BriefingWriter = LlmAgent(<br>    name=&quot;BriefingWriter&quot;,<br>    model=MODEL,<br>    output_schema=BriefingContent,  # forces valid JSON<br>    output_key=&quot;briefing&quot;,<br>    instruction=_fmt(BRIEFING_WRITER_PROMPT),<br>)</pre><p>This is where output_schema earns its keep. By passing a Pydantic model, ADK instructs the model to return JSON that exactly matches that shape. <strong>No parsing, no regex, no JSON extraction hacks.</strong> The data arrives structured and ready.</p><p>The prompt pulls URLs from {{state.resolved_sources}} — the pre-verified list from Step 2 — and matches them to stories by domain and topic. Every story is instructed to have at least one URL (even an approximate match) rather than leaving urls empty.</p><p><strong>Note:</strong> When output_schema is set, the agent cannot use tools — another Gemini constraint. BriefingWriter is pure synthesis: read state, write structure.</p><h3>Step 5 — Translator</h3><pre>class HebrewBriefing(BaseModel):<br>    tldr_he: List[str]<br>    news_items_he: List[NewsItemHe]<br>    community_pulse_he: str</pre><pre>Translator = LlmAgent(<br>    name=&quot;Translator&quot;,<br>    model=MODEL,<br>    output_schema=HebrewBriefing,<br>    output_key=&quot;briefing_he&quot;,<br>    instruction=TRANSLATOR_PROMPT,<br>)</pre><p>Same output_schema pattern. The translator reads {{state.briefing}} and produces a parallel Hebrew structure. The prompt includes specific rules: keep product names in English (Claude, GPT, Gemini, etc.), keep dates as-is, and <strong>never use ASCII double-quotes inside Hebrew strings</strong> — Hebrew abbreviations like ארה&quot;ב contain a character that breaks JSON parsing. More on this in Lessons Learned.</p><h3>Step 6 — Publisher</h3><pre>Publisher = LlmAgent(<br>    name=&quot;Publisher&quot;,<br>    model=MODEL,<br>    tools=[build_and_save_html],<br>    instruction=PUBLISHER_PROMPT,<br>)</pre><p>The final step calls a custom Python tool with 3 parameters: briefing_json, hebrew_json, and topic. The tool builds the HTML with the EN/HE toggle and saves it to output/YYYY-MM-DD/briefing_HHMMSS.html.</p><p><strong>Tool design principle:</strong> every parameter you add is a failure mode. The LLM has to name them correctly, infer their types, and fill them with reasonable values. I started with 16 parameters and got constant MALFORMED_FUNCTION_CALL errors. I reduced to 3. Rock solid.</p><h3>The Full Pipeline</h3><pre>root_agent = SequentialAgent(<br>    name=&quot;AILatestBriefing&quot;,<br>    description=&quot;Latest AI news briefing from 5 major vendors + community reactions.&quot;,<br>    sub_agents=[<br>        VendorResearcher,     # Step 1: google_search x5    → raw_vendor_news<br>        URLResolver,          # Step 2: resolve_source_urls → resolved_sources<br>        CommunityResearcher,  # Step 3: google_search x2   → raw_community<br>        BriefingWriter,       # Step 4: BriefingContent     → briefing<br>        Translator,           # Step 5: HebrewBriefing      → briefing_he<br>        Publisher,            # Step 6: HTML file           → output/<br>    ],<br>)</pre><p>6 agents. 10 lines. The entire orchestration logic.</p><p>Here’s how session state flows between them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*3FJhsc7t-oUxWm5U41WE-g.png" /></figure><p>Each agent writes one key. Downstream agents read what they need via {{state.key}}. The state store is the backbone — no direct agent-to-agent communication needed.</p><h3>The ADK Web UI</h3><p>Before running this in production, use the built-in web UI to develop and debug.</p><pre>adk web</pre><p>Open http://localhost:8000, select <strong>AILatestBriefing</strong>, send a message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsoDb_tkftX4-7xMSOZdow.png" /></figure><p>What you’ll see:</p><ul><li>Each agent step appears in the UI as it runs</li><li>Expand any step to inspect what the agent received and what it output</li><li>Session state is visible at every point — raw_vendor_news, resolved_sources, briefing, etc. as they populate</li><li>If a step fails, you can identify exactly where and why</li></ul><p>This is dramatically faster than debugging with print statements. When BriefingWriter produces no source links, you can immediately check what resolved_sources actually contains. When URLResolver doesn&#39;t call the tool, you can see exactly what its prompt looked like.</p><p><strong>One gotcha:</strong> adk web must be run from the directory containing your agent package. If you cloned the repo and ran cd ai-latest-briefing, you&#39;re already in the right place — just run adk web directly.</p><h3>Running It</h3><h3>Setup</h3><pre>git clone https://github.com/kobyal/ai-latest-briefing<br>cd ai-latest-briefing</pre><pre>python -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -r requirements.txt</pre><pre>cp .env.example .env<br># GOOGLE_API_KEY=your_key_here<br># GOOGLE_GENAI_MODEL=gemini-2.5-flash<br># LOOKBACK_DAYS=3   # covers last 3 days; set to 1 for yesterday-only, 7 for weekly digest</pre><p>Get your API key at <a href="https://aistudio.google.com/">aistudio.google.com</a> — free tier works fine.</p><h3>Run via ADK Web UI</h3><pre>adk web</pre><p>Open http://localhost:8000, select <strong>AILatestBriefing</strong>, send any message.</p><h3>Run programmatically</h3><pre>import asyncio<br>from google.adk.runners import Runner<br>from google.adk.sessions import InMemorySessionService<br>from google.genai import types<br>from ai_latest_briefing.agent import root_agent</pre><pre>async def run():<br>    session_service = InMemorySessionService()<br>    session = await session_service.create_session(<br>        app_name=&quot;briefing&quot;, user_id=&quot;u1&quot;<br>    )<br>    runner = Runner(<br>        agent=root_agent,<br>        app_name=&quot;briefing&quot;,<br>        session_service=session_service,<br>    )<br>    msg = types.Content(<br>        role=&quot;user&quot;,<br>        parts=[types.Part(text=&quot;Run the latest briefing&quot;)]<br>    )<br>    async for event in runner.run_async(<br>        user_id=&quot;u1&quot;, session_id=session.id, new_message=msg<br>    ):<br>        if event.is_final_response():<br>            print(event.content)</pre><pre>asyncio.run(run())</pre><p>Output lands in output/YYYY-MM-DD/briefing_HHMMSS.html. The pipeline takes 2-3 minutes end-to-end.</p><h3>Lessons Learned (the hard way)</h3><h3>output_schema is the most underrated ADK feature</h3><p>Forcing structured output means no regex, no JSON extraction hacks. The data just arrives clean. It also makes chaining predictable — the next agent always receives the same shape, regardless of how the model phrased its response. Use it on every synthesis step.</p><h3>Design tools for the LLM, not for you</h3><p>Your tool’s parameters are a prompt, not an API contract. The LLM has to name them correctly, infer types, and fill them with reasonable values — <em>every single call</em>. 3 parameters = reliable. 10+ parameters = silent failures.</p><p>Think of each parameter as a question you’re forcing the LLM to answer correctly before the tool runs. Keep that question count low.</p><h3>The URL problem — resolve immediately or not at all</h3><p>Gemini’s google_search grounding redirects expire in ~30-60 seconds. By the time a downstream step tries to use them, most are dead.</p><p>You can’t prompt-engineer your way around this. I tried: “output direct article URLs, not redirect URLs.” The model ignores it. It always writes the grounding redirects — this is Gemini behavior you cannot change.</p><p>The fix is architectural: <strong>URLResolver runs as Step 2</strong>, immediately after search, before the redirects expire. Adding more search steps between them (to find more URLs) made things worse — the extra time was enough to expire the originals.</p><h3>Broad queries beat date-pinned queries</h3><p>&quot;Anthropic Claude news March 22, 2026&quot; returns nothing on quiet days. &quot;Anthropic Claude latest news March 2026&quot; surfaces the most recent results naturally. Always use {month_year} in search queries, not {today}.</p><h3>Prefer recent — don’t hard-skip</h3><p>My original prompt said: skip any story older than LOOKBACK_DAYS. Clean in theory. In practice, it left vendor slots empty when a company had a quiet week.</p><p>The fix: prefer stories within the window, but if nothing was published that recently, include the most recent story available and note its actual date. Full coverage, honest dates, no empty gaps.</p><h3>output_schema + multilingual = careful escaping</h3><p>When I added Hebrew translation, I started getting JSONDecodeError. The culprit: Hebrew uses an abbreviation for &quot;USA&quot; (ארה&quot;ב) that contains an ASCII double-quote character. Inside a JSON string value, that breaks parsing.</p><p>The fix is two-pronged:</p><ol><li>Tell the Translator in its prompt to never use ASCII double-quotes inside string values</li><li>Add a multi-level fallback in your JSON parsing code: json.loads → ast.literal_eval → regex fix → empty dict</li></ol><p>Don’t assume output_schema guarantees perfectly parseable JSON in all edge cases. It&#39;s very good, not bulletproof.</p><h3>The Gemini constraint is a feature</h3><p>Being forced to split google_search agents from custom-tool agents made the pipeline more debuggable, not less. Each agent has one visible job. When something breaks, you know exactly where to look. Embrace the constraint.</p><h3>What’s Next</h3><ul><li><strong>Automate it</strong>: A cron job or GitHub Action that runs every morning at 8am</li><li><strong>More vendors</strong>: Mistral, Meta, xAI — just add queries to VENDOR_RESEARCHER_PROMPT</li><li><strong>More languages</strong>: Extend HebrewBriefing with French, Spanish, German fields</li><li><strong>Different delivery</strong>: Replace the HTML Publisher with a Slack webhook or SendGrid tool</li><li><strong>Weekly digest</strong>: Set LOOKBACK_DAYS=7 in .env</li></ul><p><em>Built with </em><a href="https://google.github.io/adk-docs/"><em>Google ADK</em></a><em> and Gemini 2.5 Flash.</em></p><p><strong>GitHub</strong>: <a href="https://github.com/kobyal/ai-latest-briefing">github.com/kobyal/ai-latest-briefing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb38bc857582" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Superpower in Q Developer: Integrating MCP Tools]]></title>
            <link>https://medium.com/@kobyal/the-hidden-superpower-in-q-developer-integrating-mcp-tools-c46c8740cc0b?source=rss-38b993992beb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c46c8740cc0b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-q]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Koby Almog]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 07:05:48 GMT</pubDate>
            <atom:updated>2025-07-08T07:05:48.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72w_UzjNic7mPfBOFSxFWA.png" /></figure><h3>Amazon Q for Developer with Model Context Protocol</h3><p>Amazon Q for Developer is AWS’s AI coding assistant that helps you write code, debug issues, and build applications. Available through the AWS Console, IDE plugins, and CLI, Q recently gained a powerful new capability: Model Context Protocol (MCP) support.</p><p>MCP is an open standard that lets AI assistants connect to external tools and data sources. Think of it as giving Q a “toolbox” — instead of just relying on its training data, Q can now use specialized tools to draw diagrams, query databases, fetch live documentation, and more.</p><p>With MCP integration, Q can now orchestrate external tools to solve problems that previously required manual effort or multiple separate applications. Whether you’re working in your IDE or terminal, Q can tap into specialized tools and live data sources to provide more accurate, up-to-date assistance.</p><p>This guide covers what MCP is, how it works with Amazon Q for Developer, setup instructions using AWS’s official MCP servers from <a href="https://github.com/awslabs/mcp">https://github.com/awslabs/mcp</a> — including live AWS documentation lookup, CDK scaffolding, architecture diagram generation, cost analysis and much more.</p><h3>What is Model Context Protocol (MCP)?</h3><p>Model Context Protocol (MCP) is an open standard that defines how AI assistants communicate with external tools and services. Originally proposed by Anthropic, MCP creates a secure, structured way for AI models to access capabilities beyond their training data.</p><p>Here’s how it works: external helper programs (called MCP servers) connect to the AI (the MCP client) through a simple communication interface. When you ask Q for something beyond its built-in knowledge — like generating a diagram, querying a database, or fetching live data — Q can invoke the appropriate tool through MCP instead of guessing or providing outdated information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Z4P1Cj_a4Q5RbcDcSirnnA.png" /><figcaption>The Q Developer + MCP Integration Flow</figcaption></figure><p>Think of MCP as the “USB-C of AI” — just as USB-C provides a universal standard for connecting any compatible device to your computer, MCP provides a universal standard for connecting any compatible tool to AI assistants. This standardization means that an MCP server built for one AI platform can work with any other MCP-compatible AI system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*wcr2asNl_YCzv9-KvXVU9g.png" /><figcaption>Anthropic MCP architecture (from ZhiHu)</figcaption></figure><p>Since MCP is an open protocol with official specifications and SDK libraries, developers can create their own MCP-compliant tools or use community-built ones. This creates a growing ecosystem where any AI platform supporting MCP can leverage the same pool of tools, making the standard incredibly powerful for extending AI capabilities.</p><h3>Enabling MCP in Amazon Q Developer CLI</h3><p>Amazon Q’s CLI acts as an MCP client, meaning it can launch and communicate with MCP servers on your machine. To integrate an MCP server, you need to configure Q CLI by adding it to a config file. Here are the basic steps and best practices:</p><h4><strong><em>1 step</em></strong></h4><p>Update Q CLI: Ensure you have Q Developer CLI v1.9.0 or later, since MCP support was added in that version .</p><h4><strong><em>2 step</em></strong></h4><p>Install Dependencies: Most AWS MCP servers are Python-based and published on PyPI, and the <strong>default and recommended way to run them is with </strong><strong>uvx</strong> (using the <a href="https://github.com/astral-sh/uv">uv package manager</a>). In almost every official AWS example, you don’t need to manually install server dependencies or clone GitHub repos — you just need:</p><h4><strong>Python 3.10+</strong><br> <em>(Most AWS MCP servers require Python 3.10 or newer).</em></h4><ul><li><strong>On Mac:</strong> brew install python@3.10 or <a href="https://www.python.org/downloads/">download from python.org</a></li><li><strong>On Ubuntu/Debian:</strong></li></ul><pre>sudo apt update<br>sudo apt install python3.10 python3.10-venv python3.10-distutils</pre><ul><li><strong>On Windows:</strong> <a href="https://www.python.org/downloads/windows/">Download the Python installer</a></li></ul><h4><strong>uv package manager</strong><br> <em>(The easiest way to run AWS MCP servers, especially those from </em><a href="https://github.com/awslabs/mcp"><em>awslabs/mcp</em></a><em>)</em></h4><ul><li><strong>On Mac:</strong> brew install uv or pip3 install uv</li><li><strong>On all systems:</strong> pip install uv or pip3 install uv</li></ul><h4>Your Q CLI at version 1.9.0 or later</h4><p><strong>You do <em>not</em> need to fiddle with Docker or Node unless:</strong></p><ul><li>The MCP server is Node-based (rare for AWS, more common for community servers)</li><li>You specifically want container isolation (then use docker)</li><li>You’re integrating a server that requires npx (for Node.js tools)</li></ul><h4>3 step</h4><p>Create the Config File: Q CLI looks for an mcp.json file to know what MCP servers to load. You can have:</p><ul><li>A global config at ~/.aws/amazonq/mcp.json (applies to all Q CLI sessions and projects on your machine)</li><li>An optional project-local config at ./.amazonq/mcp.json in a specific project directory (shared with team via version control, perhaps)</li></ul><p>If both exist, Q merges them. To get started, create the mcp.json (in the appropriate folder) and open it in an editor.</p><ul><li>Define MCP Server Entry: In the JSON, add an entry under “mcpServers” with a unique key for your MCP server, then specify how to run it. For example, to add the <strong>AWS CDK MCP server</strong>, your mcp.json might include:</li></ul><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;awslabs.cdk-mcp-server&quot;: {<br>      &quot;command&quot;: &quot;uvx&quot;,<br>      &quot;args&quot;: [&quot;awslabs.cdk-mcp-server@latest&quot;],<br>      &quot;env&quot;: {<br>        &quot;FASTMCP_LOG_LEVEL&quot;: &quot;ERROR&quot;<br>      }<br>    }<br>  }<br>}</pre><p>In this snippet, the key “awslabs.cdk-mcp-server” is just a label (you can name it freely, e.g. “postgres” or “myTool” ), and we provide:</p><p>— command: the shell command to start the server. Here uvx is used (an alias that runs a Python package in an isolated env). It could also be npx for Node packages, docker to run a container, or just python / node with a script path.</p><p>— args: the arguments for the command. In this case, we pass the package name awslabs.cdk-mcp-server@latest which tells uvx to fetch and run the latest CDK MCP server package . Some servers might require additional args (like a connection string, file path, etc.).</p><p>— env: (Optional) environment variables for the MCP server process. In our example we set a logging level variable. You might also include API keys or configuration via env vars if needed by the server. You can also configure a timeout in seconds for tool calls, if the default is not suitable.</p><p>Tip: Rather than writing this from scratch, you can copy config snippets from the AWS MCP Servers directory on GitHub or documentation. AWS provides an MCP Server Directory listing all available servers</p><p>and their config details. For instance, the snippet above was taken from the AWS CDK MCP server’s instructions. Using those verified configs helps avoid typos.</p><p><a href="https://github.com/awslabs/mcp#server-directory">GitHub - awslabs/mcp: AWS MCP Servers - helping you get the most out of AWS, wherever you use MCP.</a></p><h4>step 4</h4><p>Now start a Q CLI session by running q chat . On startup, Q will attempt to initialize any configured MCP servers. You should see in the terminal logs something like:</p><p>✓ 1 of 1 mcp servers initialized (if it loaded correctly) or error messages if something went wrong . For example, if the JSON has a syntax error, Q prints a warning like “Error reading global mcp config: expected value at line X…” and it will ignore the file. If the server command failed (maybe a missing dependency or network issue), you may see a timeout error: “x &lt;server&gt; has failed to load: Operation timed out …”, followed by “0 of 1 mcp servers initialized” . In such cases:</p><p>— Double-check your mcp.json format (a malformed JSON will be skipped entirely).</p><p>— Ensure the command and args are correct (e.g., can you run them manually?). Install any missing packages or correct the path.</p><p>— Check for additional info in Q’s debug logs. You can set Q_LOG_LEVEL=trace and find logs in $TMPDIR/qlog to diagnose initialization issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*k6ddw14k1fkRJNJg7wY5Ag.png" /><figcaption>example of successful intilizaion of mcp servers in amzon q</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2qG-R-gXufH6Rolo2BJ2A.png" /><figcaption>use /tools to check permission</figcaption></figure><h4>step 4</h4><p>Running the tool. lets say we want to build a diagram via our new mcp server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHsejjSy7iYIZGvm1O61KA.png" /><figcaption>Show a diagram of a multi-region active-active setup with Route 53 + S3 + Lambda</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYCnO-R6MuXyick5uqxuEw.png" /><figcaption>internally usage of using tools: list_icons, generate_diagrams</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*t92XLunzOhuG7Xf0B8CQDw.png" /><figcaption>summary of diagram creation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*YqNA8ZXWhG8Mw2QsPgXglg.png" /><figcaption>generated diagram</figcaption></figure><h3>Enabling MCP in Q Developer IDE Plugins</h3><p>MCP support was added to the Q for Developer IDE extensions in mid-2025, allowing the same tool integration within VS Code or JetBrains. The setup is similar in concept to the CLI, but the IDE provides a user-friendly GUI for configuration instead of editing JSON manually. Ensure you’ve updated the Q plugin to the latest version (after June 13, 2025) so that MCP features are available.</p><p>To add an MCP server in the IDE:</p><h4>step 1</h4><p>Open the MCP Configuration UI: In your IDE, open the Amazon Q chat panel. Click on the settings (gear) icon, and navigate to the MCP configuration section. This opens a form where you can manage MCP servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*b1ZM0fYTp-TpRhL7DyrPbA.png" /><figcaption>local to toolbox icon</figcaption></figure><h4>step 2</h4><p>Add a New Server: Click the “+” (plus) button to add a server scope: . You will be prompted to choose a scope</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*O0UGQSjSOdBt9bbPsmVY3A.png" /><figcaption>click the + buttom</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*r2n0PogdQNofnJW9PTr_gQ.png" /><figcaption>gui mcp configuration</figcaption></figure><p>Global (applies in all workspaces, stored in the same ~/.aws/amazonq/mcp.json as the CLI uses), or Workspace-Local (stored in a local .amazonq/mcp.json for that project directory only).</p><p>Enter Server Details: The IDE will present fields corresponding to what goes in the config:</p><p>Name — a friendly name for the server (can be anything, e.g. “AWSDocMCPServer”) .</p><p>Transport/Protocol — choose stdio (the only option currently, since Q connects via standard I/O)</p><p>Command — the command to run the server. For example, for the AWS Documentation MCP server, the command is uvx (which stands for running a tool via the uv package manager) .</p><p>Arguments — any arguments to pass. In this example, the argument is awslabs.aws-documentation-mcp-server@latest , which tells uvx to fetch that PyPI package . If multiple arguments are needed, you can add additional fields.</p><p>Environment Variables — add any required env vars. For instance, AWS’s MCP servers often accept FASTMCP_LOG_LEVEL to control logging verbosity; setting it to ERROR is recommended for minimal logs . Another example: AWS_DOCUMENTATION_PARTITION = aws (to specify using AWS public partition docs).</p><p>Timeout — an optional timeout (seconds) for tool execution, default 60 is usually fine.</p><p>Save and Configure Permissions: Click Save. The plugin will save the config (writing to the JSON under the hood) and then likely show a Tool Permissions panel. In the IDE, you can set each tool from the new server to one of three permission levels:</p><p>Ask — prompt each time (default, similar to CLI untrusted mode).</p><p>Always allow — run without prompting (trust it).</p><p>Deny — never use that tool .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*QVAZU7lkJE1djZnUKydfUQ.png" /><figcaption>setting permission for tools in mcp via gui</figcaption></figure><h4>step 3</h4><p>run a command that require the use of the new mcp server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*7PyifC2gm4ML4XjDD1UHMQ.png" /><figcaption>How do I set up S3 bucket versioning?</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EitUKJ5ZKjhcY6A4ESjiZQ.png" /><figcaption><strong>Answer based on MCP Documentation Server</strong></figcaption></figure><h3>Common Issues and Troubleshooting</h3><p>When integrating MCP with Q for Developer, you may encounter some common pitfalls. Here are issues that developers often run into, and how to resolve them:</p><p><strong>Malformed mcp.json or Config Errors</strong>: If Q CLI isn’t loading your MCP server, the first thing to check is the config file syntax. Even a stray comma or quote can cause it to fail parsing. Q will log a warning on startup if the JSON is invalid — e.g. “WARNING: Error reading global mcp config: expected value at line X…”. Use a JSON linter or validator to fix any syntax issues. Once the file is valid, restart q chat and you should see the initialization message.</p><p><strong>Server Failing to Start (Timeouts)</strong>: If the JSON is fine but Q reports a timeout or non-zero exit when initializing the MCP server (e.g., “failed to load… Operation timed out”), it means the server process didn’t come up properly. Common causes:</p><p><strong>Missing dependencies or wrong command</strong>. Double-check you installed everything required. For instance, if the command is npx@modelcontextprotocol/server-postgres , do you have Node.js and npx available? If using uvx for a Python server, do you have the uv tool installed? Installing uv (e.g., via pip install uv ) or using an alternative like pipx might be necessary</p><p><strong>No internet access </strong>(for pulling a package). The first run of an MCP server command like uvx awslabs.aws-documentation-mcp-server@latest will attempt to download the package.</p><p>Ensure your environment allows this (not behind a firewall that blocks PyPI, etc.), or pre-install the package manually.</p><p><strong>Long startup time.</strong> Some servers may take a few seconds to initialize (especially if downloading data on first run). Q’s default timeout might trigger. You can increase the timeout in config (e.g., set “timeout”: 120 in the server entry) if needed. To debug further, check Q’s logs as mentioned (set Q_LOG_LEVEL=debug or trace to see what’s happening when loading the MCP server) .</p><p><strong>Tools Not Appearing / Not Working</strong>: If Q loaded the server but you don’t see the expected behavior: Make sure the server actually initialized fully. The CLI might say “1 of 1 servers initialized,” but perhaps the server has multiple tools and one failed internally. Reviewing the server’s own output (maybe accessible in logs or by running the server standalone) could help.</p><p>Verify you used the correct key names. The key in mcp.json (e.g., “postgres” or “amazon-ivs-mcp-server” ) doesn’t matter except it’s used to namespace the tool names. However, some servers might expect certain naming conventions. The AWS CLI logs in one example showed warnings that it renamed tool names to fit a naming convention (e.g., stripping special chars). Usually you can ignore those warnings — Q is just normalizing tool IDs.</p><p>If a tool runs but returns incorrect results, ensure your inputs are correct. For instance, a database MCP server needs a proper connection string/credentials (often passed in the args or env). If Q says it cannot find data, the tool might not be pointed at the right source.</p><p><strong>Permission Prompts Every Time</strong>: If you find Q keeps asking to allow a tool repeatedly, remember to use the trust features. In CLI, press t the first time (trust for session) or run /tools trustall to allow all. In IDE, set the tool to “Always allow” in the MCP server’s permission settings.</p><p>Conversely, if you accidentally trusted something and want to revert, use /tools reset (CLI) to set all back to ask, or toggle to “Ask” in the UI.</p><p><strong>MCP Tools Not Used by Q</strong>: If you added a server but Q never seems to invoke it, consider how you’re prompting. Q will only use a tool when it “thinks” it’s needed. Try explicitly requesting the function of the tool to test it (for example: “Use the AWS CDK tool to create a new Python Lambda project”). Also ensure the tool’s capabilities are understood by Q — usually the MCP server communicates a description of its tools to Q. If a custom tool isn’t being used, you might need to phrase your request differently or confirm the tool was recognized. You can type /tools in CLI to list all tools and see that your MCP server’s tools are listed and not denied.</p><p><strong>Multiple MCP Servers</strong>: Q supports multiple servers configured at once. Just add additional entries under “mcpServers” in the JSON (or via multiple add operations in the UI). They will all load in parallel. If you load many, be mindful of system resources and potential port clashes (some servers may use local ports). There’s generally no issue using several, and Q will juggle them (e.g., you could have one server for AWS docs, one for databases, one for diagrams simultaneously). Just watch the startup logs to ensure each reports initialized. If one fails, it won’t prevent others from loading, so you might see “1 of 2 initialized” — meaning one server had an issue.</p><h3>📚 Resources</h3><ul><li><a href="https://github.com/awslabs/mcp#server-directory">GitHub - awslabs/mcp: AWS MCP Servers - helping you get the most out of AWS, wherever you use MCP.</a></li><li><a href="https://awslabs.github.io/mcp/">Welcome to AWS MCP Servers | AWS MCP Servers</a></li><li><a href="https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/mcp-ide.html#mcp-ide-configuration-access-ui">MCP configuration for Q Developer in the IDE</a></li><li><a href="https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/command-line-mcp-config-CLI.html">MCP configuration in the CLI</a></li><li><a href="https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/qdev-mcp.html">Using MCP with Amazon Q Developer</a></li><li><a href="https://aws.amazon.com/about-aws/whats-new/2025/06/amazon-q-developer-ide-plugins-mcp-tools/">Extend Amazon Q Developer IDE plugins with MCP tools - AWS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c46c8740cc0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New AWS Feature: Exposing Private Services Across Regions Using Service Endpoints]]></title>
            <link>https://medium.com/@kobyal/new-aws-feature-exposing-private-services-across-regions-using-service-endpoints-7647831386b7?source=rss-38b993992beb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7647831386b7</guid>
            <dc:creator><![CDATA[Koby Almog]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 14:37:22 GMT</pubDate>
            <atom:updated>2025-03-18T14:49:41.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*TExBUPMBIwddIM5T5dhZbg.png" /></figure><h3>Introduction</h3><p>In <strong>November 2024</strong>, AWS introduced a significant enhancement to <strong>AWS PrivateLink</strong>: <strong>Cross-Region VPC Endpoints</strong>.</p><p>I’d like to thank my colleague, <strong>Hezi Agian</strong>, who suggested I look into this feature. His recommendation led me to explore how <strong>AWS PrivateLink now enables secure, private connectivity across AWS regions</strong> — a game-changer for multi-region architectures.</p><p>For years, AWS PrivateLink enabled <strong>secure, private connectivity</strong> to AWS services and custom applications — but <strong>only within the same AWS region</strong>. This limitation forced organizations running <strong>multi-region architectures</strong> to rely on complex alternatives, such as:</p><ul><li><strong>VPC Peering</strong> — Doesn’t support overlapping CIDRs and scales poorly.</li><li><strong>AWS Transit Gateway (TGW)</strong> — Expensive and introduces additional latency.</li><li><strong>VPN / Direct Connect</strong> — Requires additional on-premises connectivity.</li></ul><p>With this new <strong>AWS PrivateLink capability</strong>, you can now <strong>expose private services across AWS regions</strong> without using <strong>public IPs, VPC Peering, or additional networking layers</strong>.</p><p><strong>Official AWS Announcement:</strong><br><a href="https://aws.amazon.com/blogs/networking-and-content-delivery/introducing-cross-region-connectivity-for-aws-privatelink/"><strong>AWS Blog: Introducing Cross-Region Connectivity for AWS PrivateLink</strong></a></p><h3>What This Means in Real-World Use Cases</h3><ul><li>You can <strong>run services privately in one AWS region</strong> and <strong>consume them in another region</strong> without public exposure.</li><li>Your applications <strong>stay entirely within AWS’s private network</strong>, reducing security risks and latency.</li><li>You can <strong>simplify your multi-region architecture</strong> without relying on <strong>VPC Peering, Transit Gateway, or complex firewall rules</strong>.</li></ul><p>To demonstrate this capability, we’ll walk through a <strong>real-world use case</strong>, where we <strong>exposed a private service (</strong><strong>q.service) from </strong><strong>us-east-1 (N. Virginia) to </strong><strong>eu-west-1 (Ireland)</strong> using <strong>cross-region PrivateLink</strong>.</p><p><strong>List of AWS Services Supporting PrivateLink:</strong><br><a href="https://docs.aws.amazon.com/vpc/latest/privatelink/integrated-services-vpce-list.html"><strong>AWS PrivateLink Supported Services</strong></a></p><p>This AWS documentation provides the full list of <strong>AWS-managed and custom services</strong> that can be accessed using <strong>PrivateLink, both intra-region and cross-region</strong>.</p><h3>Step-by-Step Guide: Setting Up Cross-Region PrivateLink</h3><p><strong>step 1 — Create a VPC Endpoint in </strong><strong>us-east-1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqI6lJeqCchC9BBx4bNKPw.png" /><figcaption>create q for developer endpoint which is available in us-east-1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5wRGUVR55jEaCeBMAKliQ.png" /><figcaption>uncheck dns name and choose proper subnets and security group</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uab7Sam8yq2YIL6b9v8XOQ.png" /><figcaption>endpoint created in us-east-1</figcaption></figure><p><strong>step 2— Create a Network Load Balancer (NLB) in </strong><strong>us-east-1</strong></p><p>create target group that points to the endpoint ips (screenshot above) — make sure to choose tcp 443</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mtx8e1ixw74Vvi5J3JHZCg.png" /><figcaption>target group for the load balancer (points to the us-east-1 endpoint)</figcaption></figure><p>now, create the nlb and connect it to the target group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlpOVWmQvdMvckjDufmhwQ.png" /><figcaption>create private nlb in us-east-1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XM2ef_UaAfNSr5ZXCTs5uA.png" /><figcaption>choose assigned from cidr or specify ip from cidr</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_To3BYxcqFySLDXenApPbw.png" /><figcaption>create proper security group (inbound https from the vpc and any to outbound), create a listener in tcp 443 which corrospond to the tcp 443 in the target group</figcaption></figure><p><strong>step 3— Create a VPC Endpoint Service in </strong><strong>us-east-1</strong></p><p>chose the nlb you just provisioned, select the supported regions this service endpoint will be used. it is recomanded to require acceptence for better security</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3cxWUPUvtKmW-IDCfvpBw.png" /><figcaption>create service endpoint in us-east-1 and expose it to eu-west-1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qElxJrz3OLxZwz2885XrHw.png" /><figcaption>note the service name of the newly created service endpoint</figcaption></figure><p><strong>step 4 — Create a VPC Endpoint in </strong><strong>eu-east-1</strong></p><p>choose endpoint services, paste the service name of the service endpoint from us-east-1, check service region us-east-1 and click “verify service”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQrZlohGguRv5ggU4fAvYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pu5RA5xwp1RPwze11aQRSg.png" /><figcaption>choose subnets and propers security group</figcaption></figure><p>this endpoints needs to be accepted in the service endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5sXQQllN0dp4l4bPxvBTA.png" /><figcaption>endpoint in eu-west-1 pointing to service endpoint in eu-west-1</figcaption></figure><p>accept the connection in the us-east-1 service endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hy0V2YiwnFcToeXN_P0itQ.png" /></figure><p>the endpoint in eu-west-1 is ready :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSv8ob52rqQJjOz6b_sHkQ.png" /><figcaption>the eu-west-1 is available</figcaption></figure><p><strong>step 5— Create route53 record to point the us-east-1 service to eu-west-1 endpoint</strong></p><p>create a private zone with the original service name. connect it to the eu-west-1 vpc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yhpoWv0nThxx3NljTgyJA.png" /><figcaption>create private hosted zone with the service name</figcaption></figure><p>create an a record (alias) to point to the the eu-west-1 endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Svp03aJNi9U8QQLSRE876g.png" /></figure><p><strong>step 6— validate the newly created endpoint</strong></p><p>open cloudshell in vpc (eu-west-1). check that it is pointing to the private endpoint and that it is usable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQhQvrnf_FEQqEUAYKItcQ.png" /></figure><h3>Summary &amp; Key Takeaways</h3><p>In this article, we explored <strong>AWS PrivateLink’s new cross-region support</strong>, introduced in <strong>November 2024</strong>, which enables <strong>secure and private connectivity between AWS regions</strong> without relying on <strong>VPC Peering, Transit Gateway, or public IPs</strong>.</p><h3>What We Did</h3><ul><li>We demonstrated how to <strong>expose a private service (</strong><strong>q.service) in </strong><strong>us-east-1 (N. Virginia)</strong> and <strong>consume it in </strong><strong>eu-west-1 (Ireland)</strong> using <strong>cross-region AWS PrivateLink</strong>.</li><li>Instead of traditional networking solutions, we leveraged <strong>VPC Endpoint Services</strong> and <strong>Interface VPC Endpoints</strong> to establish a <strong>fully private connection over AWS’s backbone</strong>.</li><li>This <strong>simplified our architecture</strong>, <strong>reduced operational complexity</strong>, and <strong>enhanced security</strong> by keeping all traffic within AWS.</li></ul><h3>Why This Matters</h3><ul><li><strong>Security &amp; Compliance</strong> → No exposure to the public internet.</li><li><strong>Performance &amp; Reliability</strong> → Uses AWS’s internal network, reducing latency.</li><li><strong>Simplicity</strong> → Eliminates the need for additional networking layers like VPNs or TGW.</li></ul><h3>Final Thoughts</h3><p>AWS <strong>cross-region PrivateLink</strong> is a <strong>game-changer for multi-region architectures</strong>, enabling <strong>private service-to-service communication</strong> across AWS regions. Whether you’re <strong>running a global application, ensuring data sovereignty, or optimizing internal service communication</strong>, this feature provides a <strong>scalable and secure</strong> solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7647831386b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting MongoDB Performance: Best Practices for AWS Lambda & Microservices]]></title>
            <link>https://medium.com/@kobyal/boosting-mongodb-performance-best-practices-for-aws-lambda-microservices-7438d1b80346?source=rss-38b993992beb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7438d1b80346</guid>
            <dc:creator><![CDATA[Koby Almog]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 13:59:34 GMT</pubDate>
            <atom:updated>2025-02-12T16:33:48.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*1r_D-otx_JSJQpXe68Bopw.jpeg" /></figure><h3>Introduction</h3><p>I’ve been working with AWS and Kubernetes long enough to know that <strong>managing database connections is one of the biggest pain points</strong> in cloud-native environments. If you’ve ever deployed MongoDB with <strong>AWS Lambda</strong> or inside <strong>Kubernetes microservices</strong>, you’ve probably faced <strong>slow connections, high latencies, or unexpected bottlenecks</strong>.</p><p>When I first integrated MongoDB Atlas with AWS Lambda, I encountered noticeable connection delays that impacted performance. After extensive troubleshooting, support tickets, and multiple optimizations, I was able to significantly reduce the latency and improve overall responsiveness.</p><p>In this guide, I’ll walk you through <strong>real-world best practices</strong> for <strong>scaling MongoDB in AWS Lambda and containerized microservices</strong>. We’ll cover:</p><ul><li><strong>Why MongoDB connections slow down in serverless &amp; microservices</strong></li><li><strong>Connection pooling &amp; reuse strategies to boost performance</strong></li><li><strong>AWS PrivateLink &amp; DNS resolution tweaks that cut latency in half</strong></li><li><strong>How to prevent MongoDB from being overwhelmed by too many microservices</strong></li></ul><p>This isn’t just theory — <strong>these are battle-tested optimizations I’ve applied in production</strong>. If you’re running MongoDB in <strong>Lambda, EKS, or a cloud-native stack</strong>, this guide will help you <strong>eliminate slow connections and unlock performance gains</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*ICVyP3JbqZdbkW6RbR1jcg.png" /><figcaption>client connection to mongo atlas via PrivateLink</figcaption></figure><h3>Why is MongoDB Slow in Cloud Environments?</h3><p>Managing database connections in cloud-native environments like AWS Lambda and Kubernetes-based microservices presents unique challenges that can lead to increased latency and performance bottlenecks. Understanding these challenges is crucial for implementing effective solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*ESUdKcaZHW9dmnUGn3zlig.png" /></figure><p><strong>Common Challenges Affecting Both AWS Lambda and Microservices:</strong></p><ul><li><strong>Improper DNS Resolution:</strong> MongoDB Atlas clusters utilize SRV (Service) records for connection strings. If not configured correctly, the database hostnames may resolve via public DNS instead of internally through a private Route 53 hosted zone, leading to unnecessary external lookups and increased latency.</li><li><strong>High Number of Concurrent Connections:</strong> Both AWS Lambda functions and microservices can generate a large number of concurrent connections to MongoDB. Each open connection consumes approximately 1MB of RAM on the MongoDB server, so a large number of connections can impact the amount of available RAM.</li></ul><p><strong>Challenges Specific to AWS Lambda:</strong></p><ul><li><strong>Ephemeral Execution Model:</strong> AWS Lambda’s stateless nature means that each new execution environment must establish a fresh database connection, adding latency due to the time required to establish these connections.</li><li><strong>Concurrency and Cold Starts:</strong> During traffic spikes, AWS Lambda scales by initiating new execution environments. Each new environment needs to establish its own database connection, leading to increased connection overhead. Implementing provisioned concurrency can mitigate cold start issues by keeping functions initialized and ready to respond.</li><li><strong>Resource Constraints:</strong> Allocating insufficient memory to a Lambda function can limit available CPU resources, leading to increased latency in establishing database connections. Monitoring Lambda metrics such as execution duration and memory usage can help identify and address these bottlenecks.</li></ul><p><strong>Challenges Specific to Microservices:</strong></p><ul><li><strong>Persistent Connections at Scale:</strong> In a microservices architecture, each service instance often maintains its own persistent connection to MongoDB. At scale, this can lead to a high number of open connections, potentially overwhelming the database server’s capacity and leading to performance degradation.</li><li><strong>Lack of Centralized Connection Management:</strong> Without a unified connection management strategy, individual microservices may keep idle connections open longer than necessary, wasting database resources. Implementing a connection pooling strategy with appropriate settings for maxPoolSize and minPoolSize ensures efficient resource utilization.</li></ul><p>By recognizing these challenges, you can implement targeted strategies to optimize MongoDB performance in both AWS Lambda and microservices environments.</p><h3>Optimize MongoDB DNS Resolution in AWS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*7CfIT7DjjQi8OJCjVYa2rA.png" /></figure><h4>Understanding SRV and TXT Records in MongoDB</h4><p>MongoDB utilizes SRV records to facilitate automatic failover and load balancing. An SRV record provides information about the available MongoDB servers and their respective ports. Additionally, a corresponding TXT record can specify connection options such as the replica set name and the authentication database.</p><p>By setting up these DNS records correctly, you enable your applications to connect efficiently to the MongoDB replica set using the mongodb+srv connection string format, ensuring optimal performance within your AWS environment.</p><ul><li>MongoDB <strong>uses SRV records</strong> to provide <strong>automatic failover and load balancing</strong>.</li><li>The <strong>MongoDB URI</strong> typically looks like this</li></ul><pre>mongodb+srv://my-mongo.mongodb.net/test</pre><p><strong>Example of SRV and TXT Records for a MongoDB Replica Set</strong></p><ul><li><strong>SRV Record:</strong></li></ul><p><strong>Name:</strong> _mongodb._tcp.cluster0.my-mongo.internal</p><p><strong>Type:</strong> SRV</p><p><strong>Value:</strong> 0 5 27017 mongo1.my-mongo.internal.</p><p><strong>Note:</strong> Ensure that each MongoDB instance (mongo1, mongo2, etc.) has corresponding A records pointing to their private IPs within the VPC.</p><ul><li><strong>TXT Record:</strong></li></ul><p><strong>Name:</strong> cluster0.my-mongo.internal</p><ul><li><strong>Type:</strong> TXT</li><li><strong>Value:</strong> &quot;authSource=admin&amp;replicaSet=rs0&quot;</li><li><strong>Explanation:</strong> This TXT record specifies the authentication database (admin) and the replica set name (rs0).</li></ul><p>To configure the SRV and TXT records in AWS Route 53, follow these steps:</p><p><strong>[1] Create a Private Hosted Zone in Route 53:</strong></p><ul><li>Navigate to the Route 53 console.</li><li>Create a new private hosted zone with a domain name, for example, my-mongo.internal.</li><li>Associate this hosted zone with your VPC.</li></ul><p><strong>[2] Add SRV Records:</strong></p><ul><li>For each MongoDB node, add an SRV record with the following details:</li><li><strong>Name:</strong> _mongodb._tcp.my-mongo.internal</li><li><strong>Type:</strong> SRV</li><li><strong>TTL:</strong> 300 seconds (or your preferred value)</li><li><strong>Value:</strong> 0 5 27017 mongo1.example.com</li><li>Repeat for mongo2.example.com and mongo3.example.com.</li></ul><p><strong>[3] Add a TXT Record:</strong></p><ul><li>Create a TXT record to specify the replica set name and authentication database:</li><li><strong>Name:</strong> my-mongo.internal</li><li><strong>Type:</strong> TXT</li><li><strong>TTL:</strong> 300 seconds</li><li><strong>Value:</strong> &quot;replicaSet=myReplicaSet&amp;authSource=admin&quot;</li></ul><p>This configuration ensures that your applications can resolve the MongoDB service internally within AWS, reducing latency and avoiding external DNS lookups. For detailed guidance, refer to MongoDB’s official documentation on SRV connection strings.</p><p>A note about creating a mongodb endpoint. when you check the “Enable DNS Name”, the relevent dns records should be created (assuming this accounts controlls the dns domain) but if it doesn’t create it for some reason you can create it yourself like shown above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmQLqJXtHKlKEN87jMm0lQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Sz-jFUtrUEpctQ84iiphA.png" /></figure><h3>Optimizing AWS Lambda MongoDB Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*g29Y9ig3UvgjpYKr0ropug.png" /></figure><h4>1. Initialize MongoDB Client Outside the Handler</h4><p>Each AWS Lambda invocation <strong>shares the same execution environment</strong> if warm. Placing the MongoClient initialization <strong>outside the handler</strong> ensures reuse across invocations.</p><p><strong>Bad (Creates a new connection for every invocation)</strong>:</p><pre>exports.handler = async (event) =&gt; {<br>  const client = new MongoClient(process.env.MONGO_URI);<br>  await client.connect();<br>  const db = client.db(&quot;test&quot;);<br>  const collection = db.collection(&quot;users&quot;);<br>  return await collection.findOne({});<br>};</pre><p><strong>Good (Persists connection across invocations)</strong>:</p><pre>const client = new MongoClient(process.env.MONGO_URI);<br>let isConnected = false;<br><br>async function connectDB() {<br>  if (!isConnected) {<br>    await client.connect();<br>    isConnected = true;<br>    console.log(&quot;MongoDB Client Connected!&quot;);<br>  }<br>}<br><br>exports.handler = async (event) =&gt; {<br>  await connectDB();<br>  const db = client.db(&quot;test&quot;);<br>  const collection = db.collection(&quot;users&quot;);<br>  return await collection.findOne({});<br>};</pre><p>No need to re-establish the connection for every invocation.</p><h4>2. Use Connection Pooling</h4><p>MongoDB <strong>drivers</strong> support connection pooling, <strong>but Lambda doesn’t maintain processes indefinitely</strong>. You need to <strong>fine-tune pool settings</strong> to match AWS Lambda’s execution model.</p><h4>Recommended Pooling Configuration</h4><pre>const mongoClientOptions = {<br>  minPoolSize: 2, // Keep at least 2 connections open<br>  maxPoolSize: 10, // Avoid excessive open connections<br>  waitQueueTimeoutMS: 5000, // Time to wait for an available connection<br>};<br>const client = new MongoClient(process.env.MONGO_URI, mongoClientOptions);</pre><p><strong>Reduces connection overhead</strong>, leading to faster query execution.</p><h4>3. <strong>Reserved Concurrency</strong></h4><p>This setting guarantees a set number of concurrent instances for your function, ensuring that critical functions have the necessary capacity.</p><ul><li><strong>How to Configure:</strong></li></ul><ol><li>Navigate to the AWS Lambda console.</li><li>Select your function.</li><li>Click on the <strong>Configuration</strong> tab.</li><li>Choose <strong>Concurrency</strong>.</li><li>Click <strong>Edit</strong>.</li><li>Select <strong>Reserve concurrency</strong> and specify the desired number.</li><li>Save the changes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*De0J4cdszWxSRq7tQqtZyw.png" /></figure><p><strong>Reference:</strong> <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html">AWS Lambda — Configuring Reserved Concurrency</a></p><h4>4. Adjusting Default Memory Allocation</h4><p>The default memory allocation for AWS Lambda functions is 128 MB, which might not be sufficient for tasks involving MongoDB operations.</p><ul><li><strong>Steps to Adjust Memory Allocation:</strong></li></ul><ol><li>Navigate to the AWS Lambda console.</li><li>Select your function.</li><li>Click on the <strong>Configuration</strong> tab.</li><li>Choose <strong>General configuration</strong>.</li><li>Click <strong>Edit</strong>.</li><li>Adjust the <strong>Memory (MB)</strong> setting as needed.</li><li>Save the changes.</li></ol><p><strong>Reference:</strong> <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html">AWS Lambda — Configuring Function Memory</a></p><h3>Best Practices for MongoDB in Microservices (EKS, Containers)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*mMx1-diK5F0Ud_g0_BnRQQ.png" /></figure><p>Microservices often run <strong>continuously</strong>, unlike Lambda, but <strong>misconfigured connection handling</strong> can still cause performance issues.</p><p>For <strong>long-lived services</strong> (e.g., running in Kubernetes on EKS), MongoDB handles <strong>connection pooling automatically</strong>. Unlike Lambda, you <strong>don’t need to manually persist connections</strong>, but <strong>you do need to size your pools correctly</strong>.</p><h4>1. Set Connection Pool Limits for Large-Scale Microservices</h4><p>When running <strong>thousands of containers</strong>, improperly configured pooling can <strong>overwhelm MongoDB</strong>. MongoDB recommends:</p><pre>const mongoClientOptions = {<br>  maxPoolSize: 100, // Prevent excessive open connections<br>  minPoolSize: 10,  // Maintain ready-to-use connections<br>  maxIdleTimeMS: 30000, // Close idle connections after 30 seconds<br>};</pre><p>Prevents <strong>excessive connections</strong>, optimizing cluster performance.</p><h4>2. Handle Connection Failures Gracefully</h4><p>In a <strong>distributed environment</strong>, network issues happen. Ensure <strong>your app can recover</strong> from a failed connection.</p><p><strong>Example: Retry logic for reconnecting</strong>:</p><pre>async function connectDB(retries = 3) {<br>  for (let i = 0; i &lt; retries; i++) {<br>    try {<br>      await client.connect();<br>      console.log(&quot;MongoDB Connected!&quot;);<br>      return;<br>    } catch (error) {<br>      console.error(`MongoDB connection failed (attempt ${i + 1}):`, error);<br>      await new Promise(res =&gt; setTimeout(res, 1000));<br>    }<br>  }<br>  throw new Error(&quot;MongoDB connection failed after retries.&quot;);<br>}</pre><p><strong>Avoids crashes</strong> when MongoDB is temporarily unavailable.</p><h3>Official MongoDB Support References</h3><p>Throughout this guide, we’ve relied on <strong>official MongoDB support recommendations</strong>. Here are some key references:</p><ul><li><a href="https://www.mongodb.com/community/forums/t/why-shouldnt-we-keep-the-db-connection-open-all-time/150530?utm_source=chatgpt.com">Why shouldn&#39;t we keep the db connection open all time</a></li><li><a href="https://www.mongodb.com/developer/products/mongodb/srv-connection-strings/">MongoDB 3.6: Here to SRV you with easier replica set connections | MongoDB</a></li><li><a href="https://www.mongodb.com/docs/manual/reference/connection-string/#dns-seedlist-connection-format">Connection Strings</a></li><li><a href="https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/#best-practices">Manage Connections with AWS Lambda</a></li><li><a href="https://www.mongodb.com/developer/languages/javascript/lambda-nodejs/">Using the Node.js MongoDB Driver with AWS Lambda | MongoDB</a></li><li><a href="https://www.mongodb.com/docs/manual/administration/connection-pool-overview/">Connection Pool Overview</a></li><li><a href="https://www.mongodb.com/docs/atlas/security-private-endpoint/">Learn About Private Endpoints in Atlas - Atlas - MongoDB Docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7438d1b80346" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securely Expose Backend Services via Private API Gateway Across AWS Accounts Using API Gateway Edge]]></title>
            <link>https://medium.com/@kobyal/frontend-to-backend-across-aws-accounts-api-gateway-vpc-link-and-service-integration-2289f8d437e1?source=rss-38b993992beb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2289f8d437e1</guid>
            <dc:creator><![CDATA[Koby Almog]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 20:09:05 GMT</pubDate>
            <atom:updated>2025-01-20T12:41:58.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWe6aMV8GveEGHc_d-u_6g.png" /><figcaption>Multi-Account Architecture: Securing Frontend-to-Backend Communication Using AWS API Gateway, VPC Link, and Private Endpoints</figcaption></figure><h3>Introduction</h3><p>In a modern cloud architecture, securely connecting frontend applications in a public AWS account to backend services in a private AWS account is a critical challenge. Our team designed a robust, scalable solution that achieves this connection using <strong>AWS API Gateway</strong> and <strong>VPC Link</strong>, ensuring secure communication while adhering to best practices.</p><p>In our setup, the frontend account hosts an <strong>API Gateway Edge</strong>, which acts as the entry point for external requests. These requests are routed via <strong>VPC Link</strong> to a <strong>private API Gateway</strong> endpoint in the backend account, which is the target of a <strong>Network Load Balancer (NLB)</strong>. The backend services can include AWS Lambda functions or microservices running on EKS. The Private API Gateway can invoke Lambda directly or forward traffic to an EKS-hosted microservice via a <strong>Network Load Balancer (NLB) → Application Load Balancer (ALB) → EKS Ingress Controller</strong>.</p><p>To further secure the architecture, we hardened the private API Gateway by implementing a <strong>resource policy</strong> that restricts access to only the private API Gateway endpoint. This ensures that only authorized traffic from the frontend API Gateway can communicate with backend services. Additionally, we used the {proxy+} resource in the API Gateway configuration to support dynamic routing for microservices and Lambda functions, simplifying the integration and scaling of backend services.</p><p>This article dives into the end-to-end flow of this architecture, from the public API Gateway Edge to the private API Gateway and backend services, highlighting key design decisions, challenges, and solutions. If you’re exploring multi-account AWS architectures or private API Gateway setups, this guide offers practical insights and actionable strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*rWe6aMV8GveEGHc_d-u_6g.png" /><figcaption>Multi-Account Architecture: Securing Frontend-to-Backend Communication Using AWS API Gateway, VPC Link, and Private Endpoints</figcaption></figure><h3>Setting Up the Frontend Account</h3><h4>Step 1: Create an Edge API Gateway</h4><ul><li>Navigate to <strong>AWS Console &gt; API Gateway</strong>.</li><li>Create a <strong>REST API</strong>.</li><li>Choose <strong>Edge-optimized</strong> as the endpoint type.</li><li>Add a <strong>/{proxy+}</strong> resource to support dynamic routing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*DoluvUFK2vV7E9V1uvxNpA.png" /><figcaption>Create Frontend API Gateway</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*6zJ-pmkfk9_lju6QL5kwdg.png" /><figcaption>create a resource in the public apigw</figcaption></figure><h4>Step 2: Create a Security Group for Private API Gateway Endpoint</h4><ul><li>Navigate to <strong>AWS Console &gt; EC2 &gt; Security Groups</strong>.</li><li>Click <strong>Create Security Group</strong>.</li><li><strong>Inbound Rules</strong>:</li></ul><p>Allow <strong>HTTPS (443)</strong> from <strong>VPC Link subnets</strong>.</p><p>Allow <strong>HTTPS (443)</strong> from <strong>Edge API Gateway CIDR range (or specific IPs if known)</strong>.</p><ul><li><strong>Outbound Rules</strong>:</li></ul><p>Allow <strong>all traffic</strong> (default rule).</p><p>Attach this security group to the <strong>VPC Endpoint that will be created next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkMZyqDxSWlk9wKiylnRQQ.png" /><figcaption>create security group for private apiexec endpoint</figcaption></figure><h4>Step 3: Create the Private API Gateway Endpoint (Frontend Account)</h4><ul><li>Navigate to <strong>AWS Console &gt; VPC &gt; Endpoints</strong>.</li><li>Click <strong>Create Endpoint</strong>.</li><li><strong>Select service name</strong>:</li><li>Look for <strong>com.amazonaws.&lt;region&gt;.execute-api</strong> (this is the API Gateway private endpoint).</li><li><strong>Choose VPC</strong>:</li></ul><p>Select the <strong>frontend account’s VPC</strong>.</p><ul><li><strong>Subnets</strong>:</li></ul><p>Choose <strong>private subnets</strong> (not public).</p><ul><li><strong>Security Group</strong>:</li></ul><p>Attach the <strong>security group created in Step 2</strong>.</p><ul><li><strong>Enable Private DNS Name</strong> (recommended for easier API calls).</li></ul><p>Click <strong>Create</strong> and <strong>note the DNS name</strong> for later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1enm_Njp5t9KgCCgquUobg.png" /><figcaption>create private apigateway endpoint — top screen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAJ0182xwr9qihntwoVGfg.png" /><figcaption>create private apigateway endpoint — bottom screen</figcaption></figure><h4>Step 4: Create a Target Group for the NLB</h4><ul><li>Navigate to <strong>EC2 &gt; Target Groups</strong>.</li><li>Click <strong>Create Target Group</strong>.</li><li>Select <strong>Target type: IP</strong> (since the Private API Gateway is an IP-based endpoint).</li><li>Choose <strong>Protocol: HTTPS (443)</strong>.</li><li>Register targets:</li></ul><p>Add the <strong>private API Gateway VPC Endpoint IPs</strong> (obtained from the VPC endpoint in Step 3).</p><ol><li>Click <strong>Create Target Group</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LN6Xy1bzQPQp8kFoGFSz1A.png" /><figcaption>retrieve the ip / ips (if multiple az) from the api gateway endpoint subnets</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Agkn7K0Dd3absLPTJlKTNg.png" /><figcaption>create target group for the nlb</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3_ksSPoNAmm_X6dsKY1iw.png" /><figcaption>register the ip / ips (if multiple az) from the api gateway endpoint subnets</figcaption></figure><h4>Step 5: Create the Network Load Balancer (NLB)</h4><ul><li>Navigate to <strong>AWS Console &gt; EC2 &gt; Load Balancers</strong>.</li><li>Click <strong>Create Load Balancer</strong> and select <strong>Network Load Balancer</strong>.</li><li>Choose <strong>Internal</strong> (since it will only be accessed within the VPC).</li><li>Select <strong>the frontend account’s VPC</strong>.</li><li>Choose the <strong>private subnets</strong> where the API Gateway endpoint is deployed.</li><li>Set up a <strong>listener</strong> on <strong>TCP 443</strong>.</li><li>Create or select a <strong>target group</strong> (next step).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kO-4KPVTX9rkADYFdVfeeg.png" /><figcaption>create internal nlb for the vpclink</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRUMzETWQEzm16AOVEHCTg.png" /><figcaption>create a listener in tcp 443 to the new target group</figcaption></figure><h4>Step 6: Create a VPC Link in API Gateway</h4><ul><li>Navigate to <strong>API Gateway &gt; VPC Links</strong>.</li><li>Click <strong>Create VPC Link</strong>.</li><li>Select the <strong>private subnets</strong> where the NLB is deployed.</li><li>Select the <strong>NLB</strong> created earlier as the <strong>target</strong>.</li><li>Click <strong>Create VPC Link</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-Z4kGOvqDzJXxiAtCC89w.png" /><figcaption>create a VPC link in frontend api gateway</figcaption></figure><h3>Setting Up the Backend Account</h3><h4>Step 1: Create a Private API Gateway</h4><ul><li>Navigate to <strong>AWS Console &gt; API Gateway</strong>.</li><li>Click <strong>Create API</strong>.</li><li>Select <strong>REST API</strong> and choose <strong>New API</strong>.</li><li>Enter <strong>API Name</strong>: backend_apigw.</li><li>Set <strong>API Endpoint Type</strong> to <strong>Private</strong>.</li><li>(Private APIs are only accessible within a VPC and require a VPC Endpoint to be reachable. For a detailed explanation, refer to the official <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started-with-private-integration.html">AWS API Gateway Private Integration Guide</a>).</li><li>Under <strong>VPC Endpoint IDs</strong>, add the previously created <strong>VPC endpoint in the frontend account </strong>(vpce-&lt;your-endpoint-id&gt;).</li><li>Click <strong>Create API</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDyBQK9lMnF2VBrR0MB3CA.png" /><figcaption>create private apigw with vpc endpoint of frontend account</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XP9DRCp-bvhBoF7_2zDbBA.png" /><figcaption>VPC link is available</figcaption></figure><h4>Step 2: Create a Resource and Method</h4><ul><li>In the <strong>API Gateway &gt; Resources</strong> section, click <strong>Create Resource</strong>.</li><li>Enter <strong>Resource Name</strong>: {proxy+} (to enable dynamic routing).</li><li>Enable <strong>API Gateway CORS</strong> if needed.</li><li>Click <strong>Create Resource</strong>.</li></ul><h4>Add a Method (ANY or Specific Methods like GET/POST)</h4><ul><li>Select the newly created {proxy+} resource.</li><li>Click <strong>Create Method</strong> and choose <strong>ANY</strong> (or select GET, POST, etc.).</li><li>Choose <strong>Integration Type</strong>: HTTP.</li><li>Enter the <strong>Endpoint URL</strong> of the backend services (e.g., Lambda, ALB, or another API).</li><li>Click <strong>Save</strong> and then <strong>Deploy API</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3roLP-G4OJwjzLahdVrzQ.png" /><figcaption>create a method under your resource and point it to a lamabda</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-92iORnc79OlDemCGgn0vQ.png" /><figcaption>the method is pointing to the lambda</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNU83TQVHDKMXZg0pJ6_9Q.png" /><figcaption>api setting to backend apigw shows that its connected via vpc endpoint of frontend account</figcaption></figure><h4>Step 3: Attach a Resource Policy to Secure the API</h4><ul><li>Navigate to <strong>API Gateway &gt; Backend API &gt; Permissions</strong>.</li><li>Click <strong>Edit Resource Policy</strong>.</li><li>Add the following policy:</li></ul><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Deny&quot;,<br>      &quot;Principal&quot;: &quot;*&quot;,<br>      &quot;Action&quot;: &quot;execute-api:Invoke&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:execute-api:&lt;region&gt;:&lt;account-id&gt;:&lt;api-id&gt;/*/*/*&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringNotEquals&quot;: {<br>          &quot;aws:sourceVpce&quot;: &quot;&lt;frontend-vpc-endpoint-id&gt;&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: &quot;*&quot;,<br>      &quot;Action&quot;: &quot;execute-api:Invoke&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:execute-api:&lt;region&gt;:&lt;account-id&gt;:&lt;api-id&gt;/*/*/*&quot;<br>    }<br>  ]<br>}</pre><h4>Step 4: Deploy the API</h4><ul><li>Click <strong>Deploy API</strong>.</li><li>Create a <strong>new stage</strong> (e.g., dev, prod).</li><li>Note the <strong>Invoke URL</strong>, which will be used by the frontend account.</li></ul><h4>Step 5: Alternative Backend: API Gateway Integration with EKS</h4><p>While this guide primarily focuses on <strong>integrating API Gateway with AWS Lambda</strong>, <strong>EKS (Elastic Kubernetes Service)</strong> can also serve as a backend. Instead of invoking a Lambda function, the <strong>Private API Gateway</strong> can route traffic to <strong>EKS microservices</strong> using a <strong>Network Load Balancer (NLB) → Application Load Balancer (ALB) → EKS Ingress Controller</strong>.</p><p>(For more details on setting up an ALB with EKS, refer to the <a href="https://docs.aws.amazon.com/eks/latest/userguide/alb-ingress.html">AWS ALB Ingress Controller documentation</a>).</p><p>How It Works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVsUk7KIwlcgZ_aSLhkM-g.png" /><figcaption>connect backend apigw to eks via nlb and alb</figcaption></figure><h4>Steps to Integrate EKS with API Gateway:</h4><p>1️⃣ <strong>Modify API Gateway Integration to Use an NLB Instead of Lambda</strong></p><ul><li>Instead of invoking Lambda, set the <strong>Private API Gateway integration target</strong> to an <strong>NLB</strong> that forwards traffic to the <strong>ALB in front of EKS</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZsOCi-QNHRkUJ4UK9YVaw.png" /><figcaption>apigw resource is pointing to nlb that is connected to alb — eks ingress</figcaption></figure><p>2️⃣ <strong>Deploy an Internal ALB for EKS Ingress</strong></p><ul><li><strong>Go to AWS Console &gt; EC2 &gt; Load Balancers</strong>.</li><li>Click <strong>Create Load Balancer</strong>, select <strong>Application Load Balancer (ALB)</strong>.</li><li>Choose <strong>Internal</strong> (not public).</li><li>Select the <strong>VPC where EKS is running</strong>.</li><li>Choose the <strong>subnets where EKS worker nodes are deployed</strong>.</li><li>Configure a <strong>listener on HTTP/HTTPS</strong>.</li></ul><p>3️⃣ <strong>Create a Target Group for ALB to Route Traffic to EKS Pods</strong></p><ul><li><strong>Go to EC2 &gt; Target Groups</strong>.</li><li>Click <strong>Create Target Group</strong>.</li><li>Choose <strong>Target Type: IP</strong>.</li><li>Register the <strong>EKS Pod IPs or the Kubernetes Service IP</strong>.</li></ul><p>4️⃣ <strong>Deploy an Ingress Resource in EKS</strong><br>If using AWS <strong>ALB Ingress Controller</strong>, apply the following <strong>Ingress YAML</strong>:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: my-service-ingress<br>  annotations:<br>    alb.ingress.kubernetes.io/scheme: internal<br>    alb.ingress.kubernetes.io/target-type: ip<br>    alb.ingress.kubernetes.io/group.name: my-ingress-group<br>spec:<br>  rules:<br>    - http:<br>        paths:<br>          - path: /my-service<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: my-service<br>                port:<br>                  number: 80</pre><p>5️⃣ <strong>Ensure API Gateway Can Reach the ALB</strong></p><ul><li><strong>Update the Private API Gateway integration request</strong> to point to the <strong>NLB</strong> (which forwards traffic to the ALB).</li><li>Ensure <strong>security groups and resource policies</strong> allow traffic from the <strong>Frontend API Gateway</strong>.</li></ul><p>✅ <strong>If you are using EKS, this method allows API Gateway to securely expose microservices instead of Lambda.</strong></p><h3>Frontend Account: Connecting the API Gateway to the Private API Gateway via VPC Link</h3><p>Now that we have created the <strong>VPC Link</strong> in API Gateway, we will configure it to route traffic <strong>directly to the Private API Gateway in the Backend Account</strong>.</p><h4>Step 1: Integrate the Frontend API Gateway with the VPC Link</h4><ul><li>Navigate to <strong>AWS Console &gt; API Gateway</strong>.</li><li>Select the <strong>Frontend API Gateway (Edge-optimized)</strong>.</li><li>In the <strong>Resources</strong> section, select the {proxy+} resource that was created earlier.</li><li>Click <strong>Create Method</strong> and select <strong>ANY</strong> (or GET/POST as required).</li><li>Choose <strong>Integration Type</strong>: VPC Link.</li><li>Select the <strong>VPC Link</strong> created in <strong>Step 6 (in frontend account)</strong>.</li><li>In the <strong>Endpoint URL</strong>, enter the <strong>Private API Gateway invoke URL</strong>, which should be in the following format:</li></ul><pre>https://&lt;private-api-id&gt;.execute-api.&lt;region&gt;.amazonaws.com/&lt;stage&gt;/{proxy}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCaBkKkYbJBrbfcFADHTew.png" /><figcaption>create method to point to the new backend apigw via private link</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QMslZjMskLJIGKCuB-mww.png" /></figure><h4>step 2: Deploy the API</h4><ul><li>Click <strong>Deploy API</strong>.</li><li>select from the current stage (e.g., dev, prod).</li></ul><h4>Step 3: Test the Connection from Frontend API Gateway</h4><ul><li>Copy the <strong>Invoke URL</strong> of the <strong>Frontend API Gateway</strong> (Edge).</li><li>Use <strong>Postman, curl, or API Gateway’s Test Console</strong> to send a request:</li></ul><pre>curl -X GET &quot;https://&lt;frontend-api-id&gt;.execute-api.&lt;region&gt;.amazonaws.com/&lt;stage&gt;/your-endpoint&quot;</pre><ul><li>Ensure the request flows through:</li><li><strong>Frontend API Gateway (Edge-optimized)</strong> → <strong>VPC Link</strong> → <strong>Private API Gateway (Backend Account)</strong> → <strong>Lambda or ALB (EKS Microservices)</strong>.</li><li>Check API Gateway logs or <strong>CloudWatch</strong> for request tracing.</li></ul><h3>🛠️ Common Issues &amp; Troubleshooting</h3><p>Even with the correct setup, AWS networking can be <strong>tricky</strong>. Below are some <strong>common issues</strong> and how to fix them.</p><h3>❌ Issue 1: API Gateway Returns “403 Forbidden”</h3><ul><li><strong>Possible Cause:</strong> The <strong>resource policy</strong> on the <strong>Private API Gateway</strong> is too restrictive, blocking requests from the frontend API Gateway.</li><li><strong>Fix:</strong> Ensure that the <strong>VPC Endpoint ID (VPCe) in the resource policy</strong> matches the <strong>actual VPC Endpoint ID of the frontend account</strong>.</li></ul><p><strong>How to Check:</strong></p><ul><li>Navigate to <strong>AWS Console &gt; API Gateway</strong>.</li><li>Select the <strong>Private API Gateway</strong>.</li><li>Click on <strong>Resource Policy</strong> (under API Gateway settings).</li><li>Look for the &quot;aws:sourceVpce&quot; condition inside the <strong>policy JSON</strong></li><li>Ensure the <strong>VPC Endpoint ID</strong> (&lt;frontend-vpc-endpoint-id&gt;) is correct.</li><li>If needed, <strong>update the policy, save changes, and redeploy the API</strong>.</li></ul><pre>{<br>  &quot;Effect&quot;: &quot;Deny&quot;,<br>  &quot;Principal&quot;: &quot;*&quot;,<br>  &quot;Action&quot;: &quot;execute-api:Invoke&quot;,<br>  &quot;Resource&quot;: &quot;arn:aws:execute-api:&lt;region&gt;:&lt;account-id&gt;:&lt;api-id&gt;/*/*/*&quot;,<br>  &quot;Condition&quot;: {<br>    &quot;StringNotEquals&quot;: {<br>      &quot;aws:sourceVpce&quot;: &quot;&lt;frontend-vpc-endpoint-id&gt;&quot;<br>    }<br>  }<br>}</pre><h3>❌ Issue 2: API Gateway Returns “504 Gateway Timeout”</h3><ul><li><strong>Possible Cause:</strong> The <strong>VPC Link is not active</strong>, or the <strong>backend Private API Gateway is unreachable</strong>.</li><li><strong>Fix:</strong></li></ul><ol><li><strong>Check VPC Link status:</strong></li></ol><ul><li>Go to <strong>API Gateway &gt; VPC Links</strong>.</li><li>Make sure it is <strong>Active</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XP9DRCp-bvhBoF7_2zDbBA.png" /><figcaption>VPC link is available</figcaption></figure><p><strong>2. Verify API Gateway logs in CloudWatch:</strong></p><ul><li>Look for timeouts or unreachable targets.</li></ul><p><strong>3. Confirm Private API Gateway is deployed correctly:</strong></p><ul><li>Navigate to <strong>API Gateway &gt; Deployments</strong>.</li><li>Ensure the correct <strong>stage and invoke URL</strong> are being used.</li></ul><h3>❌ Issue 3: Requests Fail at the Private API Gateway</h3><ul><li><strong>Possible Cause:</strong> The <strong>Private API Gateway isn’t properly integrated with backend services</strong> (Lambda/EKS).</li><li><strong>Fix:</strong></li></ul><ol><li><strong>If using Lambda:</strong></li></ol><ul><li>Check <strong>CloudWatch Logs</strong> for Lambda execution errors.</li><li>Ensure the <strong>Lambda permissions allow API Gateway to invoke it</strong>.</li></ul><p><strong>2. If using EKS (via ALB):</strong></p><ul><li>Ensure that the <strong>Application Load Balancer (ALB) is healthy</strong>.</li><li>Check <strong>ALB target groups</strong> to see if requests are reaching the backend.</li><li>Verify <strong>Ingress controller logs</strong> in EKS.</li></ul><h3>✅ Closing Thoughts: Building a Secure, Scalable API Architecture</h3><p>This guide walked you through <strong>building a multi-account API Gateway setup</strong>, securely connecting a <strong>Frontend API Gateway (Edge)</strong> to a <strong>Backend Private API Gateway</strong> using <strong>VPC Link, NLB, and Private Endpoints</strong>. By implementing this architecture, you’ve ensured:</p><p>✅ <strong>Secure API communication</strong> using <strong>VPC Link &amp; Private Endpoints</strong>, preventing unauthorized external access.<br>✅ <strong>Restricted access</strong> through <strong>resource policies</strong> and <strong>network security controls</strong>, enforcing least privilege.<br>✅ <strong>Scalability &amp; Flexibility</strong>, allowing backend services to be handled by either <strong>AWS Lambda (serverless)</strong> or <strong>EKS microservices</strong>.<br>✅ <strong>Multi-account best practices</strong>, keeping backend services isolated for <strong>better security and compliance</strong>.</p><p>While this guide primarily focused on <strong>API Gateway integration with AWS Lambda</strong>, this architecture is flexible enough to support <strong>EKS-based microservices</strong> as well. In such cases, API Gateway connects to an <strong>NLB</strong>, which forwards requests to an <strong>ALB</strong>, serving as an <strong>Ingress Controller for EKS workloads</strong>. This <strong>hybrid approach</strong> allows you to leverage both <strong>serverless (Lambda)</strong> and <strong>containerized (EKS) workloads</strong> within the same architecture, depending on your application’s needs.</p><p>By following these <strong>best practices</strong>, you can <strong>securely expose backend services across AWS accounts</strong> while maintaining <strong>performance, scalability, and isolation</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2289f8d437e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Amazon Cognito with Azure Entra ID for Secure Authentication]]></title>
            <link>https://medium.com/@kobyal/integrating-amazon-cognito-with-azure-entra-id-for-secure-authentication-6e9cba381157?source=rss-38b993992beb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e9cba381157</guid>
            <dc:creator><![CDATA[Koby Almog]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 12:49:22 GMT</pubDate>
            <atom:updated>2024-12-24T13:21:40.669Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>When integrating Amazon Cognito with Azure Entra ID (formerly Azure Active Directory), ensuring alignment with OAuth 2.0/OpenID Connect (OIDC) standards is critical. This guide outlines the steps to configure Entra ID as an external identity provider (IdP) for Amazon Cognito. Additionally, it discusses key concepts and provides background on the authentication flow, highlighting challenges and their resolutions.</p><p><strong>Note:</strong> While this guide focuses on OIDC, it’s worth noting that Amazon Cognito can also integrate with Azure Entra ID using <strong>SAML</strong>.</p><ul><li><strong>OIDC Benefits:</strong> OIDC is a lightweight, modern protocol built on top of OAuth 2.0, designed specifically for single-page applications (SPAs) and web-based use cases. It simplifies implementation with ID tokens, standard endpoints, and broad client library support.</li><li><strong>SAML Comparison:</strong> SAML is more widely adopted in legacy systems, supports enterprise-grade identity federation, and works well for large-scale, single sign-on (SSO) deployments.</li></ul><h3>Background: The Flow</h3><p>This integration follows the OpenID Connect (OIDC) protocol. The authentication flow works as follows:</p><p><strong>Step 1: Initial User Interaction</strong>:<br>The user accesses your application. Amazon Cognito serves as the authentication layer, prompting the user to log in.</p><p><strong>Step 2: Redirection to Azure Entra</strong>:<br>Cognito redirects the user to Azure Entra ID for authentication via the configured Identity Provider (IdP).</p><p><strong>Step 3: Authentication with Entra ID</strong>:<br>Users log in using their Azure Entra credentials. Upon successful authentication, Azure Entra ID issues an ID Token and optionally an Access Token.</p><p><strong>Step 4: Token Response to Cognito</strong>:<br>Azure Entra sends the tokens back to Cognito via the <strong>Redirect URI</strong> (configured in Azure Entra).</p><p><strong>Step 5: Cognito Validation</strong>:<br>Cognito <strong>trusts and accepts</strong> the tokens issued by Azure Entra ID. The validation occurs internally based on the following:</p><ul><li>The <strong>Issuer URL</strong> (e.g., https://login.microsoftonline.com/&lt;tenant-id&gt;/v2.0) configured in Cognito.</li><li>The <strong>Client ID</strong>, which matches the Azure Entra application registration.</li><li>The cryptographic signature of the tokens, validated against Azure Entra’s JWKS (JSON Web Key Set), obtained automatically via the Issuer URL.</li></ul><p><strong>Step 6: Redirect to Application</strong>:<br>After successful validation, Cognito redirects the user to the application via the specified <strong>Callback URL</strong> (set in Cognito). The application can then use the validated tokens (ID, Access) for user session management or access control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*ojq2e27uME3MI4tTIkxlOA.png" /></figure><h3>Configuring Azure Entra ID for OIDC Integration</h3><p>To begin, configure Azure Entra ID to act as the Identity Provider (IdP) for Amazon Cognito using the OpenID Connect (OIDC) protocol.</p><h4>Step 1: Register a New Application</h4><ol><li>Navigate to <strong>Azure Entra ID</strong> → <strong>App Registrations</strong>.</li><li>Click <strong>New Registration</strong> and provide the following details:</li></ol><ul><li><strong>Name</strong>: Choose a meaningful name for the application, e.g., CognitoIntegrationApp.</li><li><strong>Supported Account Types</strong>: Choose the relevant option based on your tenant’s requirements (e.g., Accounts in this organizational directory only).</li><li><strong>Redirect URI</strong>: Add the following:</li></ul><pre>https://&lt;cognito-prefix&gt;.auth.&lt;region&gt;.amazoncognito.com/oauth2/idresponse</pre><p>3. Save the registration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xX6Ci7j6y0M6Sxtya_fHGg.png" /><figcaption><strong>Redirect URI</strong></figcaption></figure><h4>Step 2: Enable ID Tokens and Configure Authentication</h4><ol><li>Navigate to the <strong>Authentication</strong> tab of your newly registered application.</li><li>Under <strong>Web Redirect URIs</strong>, confirm that the redirect URI added during registration is listed.</li><li>Scroll down to <strong>Implicit grant and hybrid flows</strong> and check <strong>ID Tokens</strong>.</li></ol><ul><li><strong>Note</strong>: While this option works, consider using the Authorization Code Flow for production environments as it provides enhanced security.</li></ul><p>4. Save the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0m1vp4vsObakSEIMB710A.png" /><figcaption>ID Tokens</figcaption></figure><h4>Step 3: Add Token Claims</h4><ol><li>Go to the <strong>Token Configuration</strong> tab.</li><li>Click <strong>Add optional claim</strong> and include attributes like email, groups, or others required by your application.</li><li>Save the configuration.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Ogs1yehM5NTc2QOBuCoWg.png" /><figcaption>Token Claims</figcaption></figure><h4>Step 4: Configure API Permissions</h4><ol><li>Navigate to the <strong>API Permissions</strong> tab.</li><li>Add the following permissions:</li></ol><ul><li><strong>Microsoft Graph</strong> → Delegated Permissions → openid, email, profile.</li></ul><p>3. Grant admin consent for the permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cADD0sisbl5i6v6k3OtjAA.png" /><figcaption>API Permissions</figcaption></figure><h3>Configuring Amazon Cognito for OIDC Integration</h3><p>Next, configure Amazon Cognito to communicate with Azure Entra ID using the OIDC protocol.</p><h4>Step 1: Set Up OIDC Provider</h4><ol><li>In the AWS Management Console, navigate to <strong>Amazon Cognito</strong> → <strong>User Pools</strong> → Select your User Pool.</li><li>Go to <strong>Identity Providers</strong> → <strong>Social and External Providers</strong> → <strong>Add Provider</strong> → <strong>OIDC</strong>.</li><li>Fill in the following:</li></ol><ul><li><strong>Provider Name</strong>: A meaningful name, e.g., AzureEntra.</li><li><strong>Issuer URL</strong>:</li></ul><pre>https://login.microsoftonline.com/&lt;tenant-id&gt;/v2.0</pre><ul><li><strong>Client ID</strong>: Enter the Application (Client) ID from Azure Entra.</li><li><strong>Client Secret</strong>: Enter the secret key generated in Azure Entra.</li><li><strong>Scopes</strong>: Add openid, profile, email.</li><li>Select <strong>POST</strong> as the Attribute Request Method.</li></ul><p>4. Save the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzZuN_5L9lQTr-_cQNXLRw.png" /><figcaption>OIDC Provider</figcaption></figure><h4>Step 2: Map Attributes</h4><ol><li>Navigate to the <strong>Attribute Mapping</strong> section in Cognito.</li><li>Map Azure Entra attributes to Cognito attributes:</li></ol><ul><li>sub → username</li><li>email → email</li><li>name → name</li><li>profile → profile</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*VPWlGT373fAIQawbWl-1XA.png" /><figcaption>attribute under oidc provider</figcaption></figure><h4>Step 3: Configure App Client</h4><ol><li>Go to <strong>App Clients</strong> in the Cognito User Pool.</li><li>Edit your App Client settings and ensure the following:</li></ol><ul><li><strong>Callback URL</strong>: Add the URL where Cognito should redirect after authentication. This should be the <strong>application’s URL</strong> (not Cognito). For example:</li></ul><pre>https://your-app-domain.com/callback</pre><ul><li><strong>Logout URL</strong>: Add the appropriate Logout URL, such as the <strong>application’s login page</strong>.<br>Example: <a href="https://your-app-domain.com/logout">https://your-app-domain.com/logout</a></li><li><strong>OAuth 2.0 Grant Types</strong>: Ensure <strong>Authorization Code Grant</strong> is enabled.</li><li><strong>OIDC Scopes</strong>: Add the required OpenID Connect (OIDC) scopes:<br>openid, profile, email.<br>For detailed instructions and additional configuration options, refer to the <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-oidc-idp.html">AWS documentation on OIDC Identity Providers</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s16fNDtCE3cOO0pupFUPBA.png" /><figcaption>App Client</figcaption></figure><h3>Best Practices</h3><ul><li><strong>Use Authorization Code Flow in Production</strong>: For better security, avoid using implicit flows. Authorization Code Flow prevents exposing tokens directly in URLs.</li><li><strong>Secure Client Secrets</strong>: Ensure the Client Secret from Azure Entra is stored securely and never exposed in application code.</li><li><strong>Regularly Review Permissions</strong>: Check and validate the permissions granted in Azure Entra to avoid exposing unnecessary data.</li></ul><h3>Conclusion</h3><p>Integrating Amazon Cognito with Azure Entra ID using OIDC is a robust way to provide secure and scalable authentication for your applications. By following the steps outlined above, you ensure a seamless experience for users while adhering to modern security practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e9cba381157" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>