<?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[Clerion - Medium]]></title>
        <description><![CDATA[cloud first,  innovation always. - Medium]]></description>
        <link>https://medium.com/clerion?source=rss----4c23810537fe---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Clerion - Medium</title>
            <link>https://medium.com/clerion?source=rss----4c23810537fe---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:13:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/clerion" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Joker Turkiye partners with Clerion to power Turkey’s first real-time TV quiz at scale]]></title>
            <link>https://medium.com/clerion/joker-turkiye-partners-with-clerion-to-power-turkeys-first-real-time-tv-quiz-at-scale-8360c99218ff?source=rss----4c23810537fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/8360c99218ff</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[scale]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <dc:creator><![CDATA[Mahir Berkan Oğuz]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 07:35:34 GMT</pubDate>
            <atom:updated>2026-07-13T07:35:35.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>About Joker Turkiye</h3><p>Joker Turkiye is an early-stage entertainment and mobile gaming company that built Turkey’s first real-time second-screen TV experience. The Joker platform synchronizes a live mobile quiz application with a prime-time television broadcast, letting viewers across the country answer trivia questions on their smartphones in real time while watching the show on TV.</p><p>The platform features live TV quiz synchronization, a 1v1 Duel Mode, a strategic joker power-up system (including 50/50 and time freeze), weekly leaderboards spanning Bronze to Diamond tiers, and a TV Studio Invitation program for its top mobile performers. Joker is available on iOS and Android and broadcasts every evening at prime time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrlKcvrocYHuuxrphr8XNw.jpeg" /></figure><h3>The Challenge</h3><p>Joker Turkiye’s core proposition real-time TV-to-mobile synchronization during prime-time broadcasts creates one of the most demanding infrastructure challenges in consumer applications: a predictable, massive, near-instantaneous concurrent spike every evening at 20:00.</p><p>When a question appears on live TV, millions of users open the app and submit answers within the same 30-second window, taking traffic from near-zero to full peak in under sixty seconds. Fixed capacity or slow reactive autoscaling would fail at the exact moment that matters most. Any latency beyond a couple of seconds degrades competitive fairness and erodes user trust, the real-time leaderboard must stay accurate under millions of concurrent writes, and a failed deployment during a live broadcast would be a public, brand-damaging incident with an uptime SLA to the TV partner on the line.</p><p>Joker needed a greenfield cloud architecture that could absorb the nightly spike, keep answers and rankings real-time, deploy safely even mid-broadcast, and remain cost-efficient without paying for peak capacity around the clock.</p><h3>The Solution</h3><p><em>Clerion</em> designed and built a greenfield, cloud-native AWS architecture purpose-built for the nightly spike, running multi-AZ in eu-central-1 (Frankfurt) for the lowest latency to the Turkish user base. Containerized microservices run on Amazon ECS Fargate with scheduled pre-warming capacity scales up thirty minutes before the broadcast and back down afterward layered with request-based autoscaling during the show. Amazon DynamoDB in on-demand mode serves as the primary data store, absorbing millions of concurrent answer submissions at single-digit-millisecond latency, while Amazon ElastiCache for Redis powers the real-time sorted-set leaderboard and enforces answer deduplication and rate limiting.</p><p>AWS Lambda with provisioned concurrency handles the time-critical TV broadcast synchronization events, eliminating cold starts on the path that matters most. Blue/green deployments with automatic circuit-breaker rollback enable zero-downtime updates and protect live broadcasts from failed releases, and Amazon CloudFront with S3 delivers mobile assets while AWS Secrets Manager centralizes credentials. The result is a serverless-first platform engineered to sit quiet by day and carry the entire country the moment the show begins.</p><h3>Results</h3><p>Under load testing that simulated one million concurrent users, the platform sustained p99 API response times under 350ms with zero DynamoDB throttling, and held above 99.95% availability during broadcast windows across its first 90 days of operation with automatic rollback absorbing deployment incidents before any viewer-visible impact. Because the architecture is serverless-first, AWS cost is concentrated in nightly peak hours with minimal off-peak spend, giving an early-stage startup prime-time-grade capacity without paying for it 24/7. Partnering with Clerion reduced infrastructure risk while improving reliability and setting the stage for future growth in new game modes and seasonal events.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8360c99218ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clerion/joker-turkiye-partners-with-clerion-to-power-turkeys-first-real-time-tv-quiz-at-scale-8360c99218ff">Joker Turkiye partners with Clerion to power Turkey’s first real-time TV quiz at scale</a> was originally published in <a href="https://medium.com/clerion">Clerion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Run Scarce GPU Workloads Across 6 AWS Regions With Step Functions for “Viewcraft”]]></title>
            <link>https://medium.com/clerion/how-we-run-scarce-gpu-workloads-across-6-aws-regions-with-step-functions-for-viewcraft-4950c3a8444c?source=rss----4c23810537fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/4950c3a8444c</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Mahir Berkan Oğuz]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 11:03:16 GMT</pubDate>
            <atom:updated>2026-07-10T11:03:18.351Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>You want to launch a g6e instance to run an AI image generation. You ask a region for one. The region says no, not right now, no capacity. This is the constraint that shaped everything we built for Viewcraft’s GPU infrastructure, and it’s the reason the system spans six AWS regions instead of living comfortably in one.</blockquote><p>This post is about running scarce GPU workloads across multiple regions: why we did it, how we orchestrate it with AWS Step Functions, and the challenges we hit along the way; cold starts, warm-up times, and the ever-present hunt for g6e capacity. It’s written for engineers, so it leans on the tradeoffs and the dead ends rather than the highlight reel.</p><h4>The real problem: g6e capacity is scarce</h4><p>Viewcraft runs its AI image generation on <strong>g6e instances</strong>, which carry NVIDIA L40S GPUs. They’re the right hardware for the workload. The problem is that they’re hard to get. Capacity is limited, not every region has them available when you ask, and during GPU crunches a given region will simply refuse to launch one.</p><p>Once you accept that a single region cannot be relied on to hand you a GPU on demand, the architecture has to change. You stop thinking “launch an instance” and start thinking “find a region that will actually give me one.” That is fundamentally a <strong>capacity</strong> problem, and going multi-region is how we solve it.</p><h4>Two levers, two different reasons</h4><p>It’s worth being precise about this up front, because it’s easy to conflate the two and get the reasoning backwards:</p><ul><li><strong>Multi-region orchestration is about capacity.</strong> We spread across regions because g6e is scarce and we need somewhere (anywhere) that will give us a GPU.</li><li><strong>Instance lifecycle (stopped or terminated) is about cost.</strong> We keep GPUs from running idle because idle GPU time is expensive. This has nothing to do with which region they’re in.</li></ul><p>Keeping these separate in your head matters, because the right answer for capacity (scan widely across regions) pulls in a different direction from the right answer for cost (keep as few things running as possible). The interesting part of the design is where those two pressures meet.</p><h3>Multi-region orchestration with Step Functions</h3><p>Our approach to capacity scarcity is deliberately unglamorous: try regions one at a time, in priority order, until one gives us an instance. AWS Step Functions is an excellent fit here because the whole thing is really just a state machine with error handling and <strong>Step Functions</strong> makes that readable and debuggable instead of burying retry logic somewhere in application code.</p><p>The state machine tries six regions in priority order:</p><ol><li>eu-central-1</li><li>us-east-1</li><li>us-east-2</li><li>eu-south-2</li><li>eu-north-1</li><li>eu-south-1</li></ol><p>Each region attempt calls a <strong>Lambda function</strong> that handles the actual EC2 API call. The Lambda has its own resilience two attempts with exponential backoff so a transient hiccup doesn’t immediately burn a region. If the <strong>Lambda</strong> ultimately fails for that region (no capacity, a launch error, whatever), the state machine <em>catches</em> the error and falls through to the next region in the list.</p><p>The shape of it is simple enough to hold in your head:</p><blockquote><em>Try Region → Check Result (Choice state) → Success, or fall through to the next region.</em></blockquote><p>If all six regions fail, the state machine terminates with a NoCapacityAvailable error. That&#39;s rare, but it happens during the worst GPU crunches, and it&#39;s genuinely useful that it fails loudly with a named error rather than hanging or silently degrading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*MGs5AuIrK6F_6XE98MF6hA.png" /><figcaption>Step Functions Diagram</figcaption></figure><p>Notably, we do this <strong>sequentially</strong>, not in parallel more on why in the lessons section, but it’s one of the decisions I’m most confident about in hindsight.</p><h3>ECS for backend and frontend</h3><p>Everything that isn’t the GPU fleet runs on ECS. Viewcraft’s backend API and frontend are both deployed as ECS services. This gives us container orchestration rolling deploys, health-managed tasks, straightforward scaling without taking on the operational weight of running Kubernetes ourselves. For a workload where the genuinely hard part is the GPU layer, we didn’t want to also be babysitting a control plane.</p><p>The request flow is straightforward: a user hits the frontend, the ECS-hosted backend receives the request, and when GPU work is needed the backend triggers a Step Functions execution. Step Functions finds a region, gets an instance serving, and the result flows back to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFZNV8pIlTnMXwIur6iDBA.png" /></figure><p>The separation matters. The ECS layer is stateless, cheap, and elastic; the GPU layer is expensive, scarce, and slow to warm. Decoupling them means the easy-to-scale part scales freely and the orchestration logic only has to reason about the hard part.</p><h3>Cost efficiency: don’t pay for idle GPUs</h3><p>Multi-region solves capacity. It does nothing for cost if anything, spreading out makes it easier to accidentally leave expensive hardware running in places you’ve forgotten about. The cost lever is separate: <strong>instance lifecycle</strong>. An idle, running g6e is the most expensive way to have a GPU ready, so we don’t do that. Instead we choose between two cheaper states depending on the latency we can tolerate:</p><ul><li><strong>Terminated: </strong>you pay nothing while idle, but a cold start means launching a fresh instance from an AMI. Cheapest, slowest.</li><li><strong>Stopped: </strong>you pay only for the EBS volume while idle, and starting the instance is far faster than a fresh launch. A little standing cost, much faster start.</li></ul><p>Here’s where the two pressures meet, and it explains something that might otherwise look inconsistent. Our capacity-hunting path scans all <strong>six</strong> regions, because launching fresh from an AMI costs nothing until it succeeds, so you can afford to look everywhere. But <strong>stopped</strong> instances carry a standing EBS cost, and you can’t afford to keep those warm in every region. So we keep stopped-and-ready instances in a smaller subset the state machine that starts stopped instances fails over across <strong>three</strong> regions (us-east-1 → us-east-2 → us-west-2), not six. Wide net for capacity, narrow footprint for cost. The two region counts aren’t a contradiction; they’re the two levers pulling in their natural directions.</p><h3>Challenges</h3><p>The reframe above is clean in hindsight. Getting there was not. Here are the challenges that actually shaped the system.</p><h4>G6e capacity scarcity</h4><p>This is the root of everything. L40S-backed g6e instances are in genuinely short supply, and availability shifts region to region and hour to hour. There’s no clever trick that makes a region give you a GPU it doesn’t have the only real answer is to try more places, which is exactly what the six-region state machine does. Every other design choice downstream is a consequence of this one hard fact.</p><h3>Cold start, the three iterations it took</h3><p>Getting a GPU is only half the battle. Once you have the instance, it has to become <em>ready to serve</em>, and that took us three iterations to get right.</p><p><strong>Phase: the naive approach (~10–12 minutes).</strong> The first version launched a fresh g6e from a base AMI (~2–3 min), downloaded the ~24 GB model onto the instance (~3–5 min and <em>unreliable</em> S3 bandwidth varies, cross-region downloads are slow, and sometimes it failed outright), then loaded the model into GPU VRAM (~45 s). Ten to twelve minutes from request to ready. The download step was the villain: not just slow, but the single most likely thing to fail and send the whole attempt back to square one.</p><p><strong>Phase 2: bake the model into the AMI (~4–6 minutes).</strong> If downloading 24 GB every cold start is the worst part, stop downloading it. We built custom AMIs with the model weights pre-baked onto the EBS volume, so the instance boots with the model already on disk and the download step disappears. Cold start dropped to roughly four to six minutes just launch plus VRAM load. The tradeoff: the AMI now has to exist in every region, so a model update means rebuild the AMI and copy it out before anyone can serve the new version.</p><p><strong>Phase 3: stopped instances with health checks (~3–4 minutes).</strong> The insight: starting a stopped instance (~30–60 s) is far faster than launching a fresh one (~2–3 min). So we keep pre-configured g6e instances stopped-but-ready, AMI baked, EBS volume warm and start them on demand. The VRAM load adds only about 45 seconds, so getting a stopped instance from start to serving is quick, and the total sits comfortably in the three-to-four-minute range. This is the state machine that fails over across the three regions above.</p><p>The evolution in one line: <strong>naive launch-and-download → AMI-baked launch → stopped instances plus health checks.</strong></p><h3>Cold-start times and the first-generation wait</h3><p>Cold-start time is not the same as the time the first user actually waits. Once an instance reports ready, the <em>first generation</em> on a freshly warmed GPU still has to run, and that first request tends to be the slowest one the instance ever serves. So the real user-perceived latency on a cold path is cold start plus first generation:</p><blockquote><em>~3–4 minutes cold start + ~1–6 minutes for the first generation (depending on image quality and output specs) = roughly 4–10 minutes total for the first user.</em></blockquote><p>This is the number that actually matters to a person staring at a loading spinner, and it’s worth measuring and quoting separately from the infrastructure cold start, because they get conflated constantly.</p><h3>Knowing when “started” means “ready”</h3><p>A <em>started</em> instance is not a <em>ready</em> instance. EC2 will happily report the instance as running while the inference server is still loading the model into VRAM and can’t accept a single request. Our answer is a <strong>health-check Lambda</strong> that polls port 8000 where the inference server listens and the state machine refuses to report success until the server actually responds. The poll runs with about a 9.5-minute timeout. We don’t expect a healthy start to take anywhere near that; the timeout is generous precisely because occasionally things are slow, and its size is an honest measure of how much uncertainty is still in the system.</p><h3>Cross-region AMI management</h3><p>Baking the model into the AMI fixed the download problem but created an operational one that grows with every region: each model update means rebuilding the AMI and copying it to all the regions that need it before any of them can serve the new version. It’s the kind of overhead that’s easy to underestimate and quietly compounds as the fleet spreads.</p><h3>Lessons learned</h3><h4>Separate your capacity strategy from your cost strategy</h4><p>The single most useful mental shift was refusing to conflate the two. Multi-region exists for capacity; instance lifecycle exists for cost. Once we stopped treating “which regions” and “stopped vs terminated” as one decision, both got clearer and the six-vs-three region footprint stopped looking like an inconsistency and started looking like the correct answer to two different questions.</p><h4>Sequential failover is simpler than parallel and cheaper</h4><p>Trying all regions at once feels faster on paper. Sequential won on every axis that mattered. It’s far easier to reason about and debug at any moment the state machine is trying exactly one region, and the execution history reads like a story. And you <strong>don’t pay for failed parallel launches</strong>: fire six launches at once and you may start several GPU instances before you can cancel the extras, which is not where you want surprise spend.</p><h4>Health checks are non-negotiable</h4><p>Every layer of infrastructure will cheerfully report success before your application can do its job. Without the health-check Lambda gating success on a real response from port 8000, we’d routinely route users to instances that aren’t serving yet. The health check is what makes “success” mean something.</p><h4>Model size drives every architectural decision</h4><p>Every phase of the cold-start journey is a response to one fact: the model is 24 GB. The download was slow because it’s big. The AMI copy overhead exists because it’s big. The unavoidable VRAM load exists because it’s big. Measure your model early and let that number drive the design, because it will whether you plan for it or not.</p><h4>Be honest about the tradeoffs</h4><p>None of this is free. Stopped-but-ready instances mean paying for idle EBS. The baked-AMI strategy means ongoing pain managing images across regions on every model change. The 9.5-minute health-check timeout is a standing admission that we can’t fully predict how long a start will take. This is a set of deliberate tradeoffs, not a trick that made the costs vanish.</p><h4>What’s next</h4><p>The obvious next frontier is keeping some capacity genuinely <em>warm </em>instances running with the model already in VRAM so the fastest path skips the load entirely, balanced against the cost of paying for idle GPUs. We’re also weighing a container-based orchestration layer for the GPU fleet for finer-grained control than the stopped-instance model gives us. Both come back to the same tension that runs through this whole system: how much are you willing to pay to keep a scarce, expensive resource ready for a request that hasn’t arrived yet? We don’t think that question has a permanent answer just a current best one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4950c3a8444c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clerion/how-we-run-scarce-gpu-workloads-across-6-aws-regions-with-step-functions-for-viewcraft-4950c3a8444c">How We Run Scarce GPU Workloads Across 6 AWS Regions With Step Functions for “Viewcraft”</a> was originally published in <a href="https://medium.com/clerion">Clerion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes + GitOps from Scratch: A Hands-On Guide with ArgoCD, HPA, and Karpenter]]></title>
            <link>https://medium.com/clerion/kubernetes-gitops-from-scratch-a-hands-on-guide-with-argocd-hpa-and-karpenter-3188a99c7647?source=rss----4c23810537fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/3188a99c7647</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Mahir Berkan Oğuz]]></dc:creator>
            <pubDate>Sat, 23 May 2026 22:59:32 GMT</pubDate>
            <atom:updated>2026-10-23T08:55:45.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkpIEq1w5myU2mNpboV85A@2x.png" /></figure><p>Build a complete GitOps pipeline on your laptop from writing your first Deployment to watching pods autoscale under load.</p><p>I’m a cloud engineer working on AWS infrastructure day-to-day, and I wanted a structured way to deepen my Kubernetes and GitOps knowledge outside of client work. This post is the result. A self-contained learning project I built on my laptop, written up as the tutorial I wish I’d had when I started. Everything here runs locally; no cloud bill required.</p><h3><strong>What We’re Building</strong></h3><p>By the end of this guide, you’ll have:</p><ul><li>A Go microservice running in Kubernetes (minikube)</li><li>ArgoCD deploying your app via GitOps (App of Apps pattern)</li><li>GitHub Actions CI that builds, pushes, and triggers deployments automatically</li><li>HPA scaling pods up/down based on CPU load</li><li>A conceptual understanding of Karpenter for node-level autoscaling on AWS</li></ul><p><strong>No AWS account needed</strong> for steps 1–6. Everything runs locally on minikube.</p><h3><strong>Architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rox5K1YCgRlJlclc1axYUQ.png" /></figure><p>Two repos, two concerns:</p><ul><li><strong>learning-app-src</strong>: your application code, Dockerfile, CI pipeline</li><li><strong>learning-app-gitops</strong>: Kubernetes manifests as Helm charts, ArgoCD Application definitions</li></ul><p>Why two repos? If manifests lived alongside source code, every CI commit (updating the image tag) would trigger another CI run, creating an infinite loop. Separating them cleanly splits “build” from “deploy.”</p><h3><strong>Prerequisites</strong></h3><ul><li><strong>Docker:</strong> Container runtime + image building</li><li><strong>kubectl:</strong> Kubernetes CLI</li><li><strong>minikube:</strong> Local K8s cluster</li><li><strong>Helm:</strong> Package manager (installs ArgoCD, templates charts)</li><li><strong>Git + GitHub account:</strong> Version control + CI/CD</li><li><strong>Docker Hub account:</strong> Public image registry</li></ul><h4><strong>Why minikube over kind or k3d?</strong></h4><ul><li><strong>Built-in addons</strong>: minikube addons enable metrics-server / ingress, one command, no manual debugging</li><li><strong>Convenient extras</strong>: minikube tunnel for LoadBalancer services, built-in dashboard for visual learning</li><li><strong>Single-binary install</strong> with sensible defaults, less time fighting the tool, more time learning Kubernetes</li></ul><h3><strong>Step 1: Start Your Cluster</strong></h3><pre>minikube start<br>kubectl config current-context # Should show: minikube<br>kubectl cluster-info # Verify connectivity</pre><blockquote>Always verify your context before applying anything. In production you might have 5 clusters configured — one wrong kubectl apply and you’ve deployed dev code to prod.</blockquote><h3><strong>Step 2: The Microservice</strong></h3><p>A Go HTTP service with four endpoints:</p><ul><li><strong>GET /</strong> — Pod info (hostname, version, Redis status)</li><li><strong>GET /healthz </strong>— Liveness/readiness: checks Redis connectivity</li><li><strong>GET /metrics</strong> — Prometheus format for monitoring</li><li><strong>GET /load?duration=10s</strong> — Burns CPU: triggers HPA scaling</li><li><strong>GET /ui/</strong> — Web dashboard with load generator button</li></ul><p><strong>Why Go?</strong> The final Docker image is 12MB (scratch base + static binary). Fast startup means HPA can react quickly, so you’re not waiting 30 seconds for Python containers to boot during scale-up.</p><h4><strong>Dockerfile (multi-stage)</strong></h4><pre>FROM golang:1.22-alpine AS builder<br>WORKDIR /app<br>COPY go.mod ./<br>COPY main.go .<br>COPY static/ ./static/<br>RUN go mod tidy<br>RUN CGO_ENABLED=0 GOOS=linux go build -ldflags=&quot;-s -w&quot; -o /server .<br><br>FROM scratch<br>COPY --from=builder /server /server<br>EXPOSE 8080<br>ENTRYPOINT [&quot;/server&quot;]</pre><p>Build and load into minikube:</p><pre>docker build -t learning-app:0.1.0 .<br>minikube image load learning-app:0.1.0</pre><h3><strong>Step 3: Kubernetes Manifests (By Hand First)</strong></h3><p>Before ArgoCD automates anything, deploy manually so you understand each resource.</p><h4><strong>Namespace</strong></h4><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: learning-app</pre><p>A logical boundary, all resources live together, easy to nuke with kubectl delete ns learning-app.</p><h4><strong>ConfigMap</strong></h4><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: learning-app-config<br>  namespace: learning-app<br>data:<br>  REDIS_ADDR: &quot;redis:6379&quot;</pre><p>Externalizes config from the image. Change Redis address without rebuilding or editing the Deployment.</p><h4><strong>Deployment (key concepts)</strong></h4><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: learning-app<br>  namespace: learning-app<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: learning-app<br>  template:<br>    metadata:<br>      labels:<br>        app: learning-app<br>    spec:<br>      containers:<br>        - name: learning-app<br>          image: learning-app:0.1.0<br>          imagePullPolicy: Never<br>          ports:<br>            - containerPort: 8080<br>          envFrom:<br>            - configMapRef:<br>                name: learning-app-config<br>          resources:<br>            requests:<br>              cpu: 100m<br>              memory: 64Mi<br>            limits:<br>              cpu: 500m<br>              memory: 128Mi<br>          livenessProbe:<br>            httpGet:<br>              path: /healthz<br>              port: 8080<br>          readinessProbe:<br>            httpGet:<br>              path: /healthz<br>              port: 8080</pre><p><strong>Critical fields explained:</strong></p><ul><li><strong>resources.requests</strong>: what the scheduler guarantees your pod. HPA uses this as the baseline: utilization = actual / requests × 100%</li><li><strong>resources.limits</strong>: the ceiling. CPU gets throttled; memory gets OOM-killed.</li><li><strong>livenessProbe</strong>: “Is this container stuck?” → Kubernetes restarts it</li><li><strong>readinessProbe</strong>: “Can it serve traffic?” → removed from Service endpoints if failing</li><li><strong>imagePullPolicy: Never</strong>: for locally-loaded images in minikube</li></ul><h4><strong>Service</strong></h4><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: learning-app<br>  namespace: learning-app<br>spec:<br>  selector:<br>    app: learning-app<br>  ports:<br>    - port: 80<br>      targetPort: 8080</pre><p>Creates a stable DNS name (<strong>learning-app.learning-app.svc.cluster.local</strong>) and load-balances across pods. The selector must match your pod labels — that’s how Services find their backends.</p><h4>Ingress</h4><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: learning-app<br>  namespace: learning-app<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>    - http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: learning-app<br>                port:<br>                  number: 80</pre><p>L7 HTTP routing. Requires an Ingress Controller (nginx) running in the cluster:</p><pre>minikube addons enable ingress</pre><p>Deploy everything:</p><pre>kubectl apply -f k8s/namespace.yaml<br>kubectl apply -f k8s/configmap.yaml<br>kubectl apply -f k8s/redis.yaml<br>kubectl apply -f k8s/deployment.yaml<br>kubectl apply -f k8s/service.yaml<br>kubectl apply -f k8s/ingress.yaml</pre><h3><strong>Step 4: GitOps with ArgoCD</strong></h3><p>Now that you understand what each manifest does, let’s automate deployment with ArgoCD.</p><h4><strong>What is GitOps?</strong></h4><p><strong>Git is the single source of truth.</strong> You declare desired state in a repo, a controller (ArgoCD) continuously makes the cluster match.</p><ul><li>Change a manifest in Git → ArgoCD applies it</li><li>Someone does <em>kubectl edit</em> manually → ArgoCD reverts it (self-healing)</li><li>Delete a resource from Git → ArgoCD deletes it from the cluster (pruning)</li></ul><h4><strong>Install ArgoCD</strong></h4><pre>kubectl create namespace argocd<br>helm repo add argo https://argoproj.github.io/argo-helm<br>helm repo update<br>helm install argocd argo/argo-cd --namespace argocd --wait</pre><h4><strong>Gitops Repo Structure</strong></h4><pre>learning-app-gitops/<br>├── root-app.yaml # Apply ONCE - manages everything below<br>├── apps/<br>│ └── learning-app.yaml # ArgoCD Application → points to chart<br>└── charts/<br>└── learning-app/<br>├── Chart.yaml<br>├── values.yaml # CI updates image.tag here<br>└── templates/ # Your K8s manifests as Helm templates</pre><h4><strong>App of Apps Pattern</strong></h4><p>Instead of manually applying each Application, one root Application watches a directory:</p><pre># root-app.yaml — the ONLY kubectl apply you ever do !!!<br>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: root-app<br>  namespace: argocd<br>spec:<br>  project: default<br>  source:<br>    repoURL: https://github.com/mahirberkano/learning-app-gitops.git<br>    targetRevision: main<br>    path: apps<br>  destination:<br>    server: https://kubernetes.default.svc<br>    namespace: argocd<br>  syncPolicy:<br>    automated:<br>      prune: true<br>      selfHeal: true</pre><p>Add a new microservice? Drop a YAML in apps/. Root app picks it up automatically.</p><h4><strong>The Application resource</strong></h4><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: learning-app<br>  namespace: argocd<br>spec:<br>  project: default<br>  source:<br>    repoURL: https://github.com/mahirberkano/learning-app-gitops.git<br>    targetRevision: main<br>    path: charts/learning-app<br>    helm:<br>      valueFiles:<br>        - values.yaml<br>  destination:<br>    server: https://kubernetes.default.svc<br>    namespace: learning-app<br>  syncPolicy:<br>    automated:<br>      prune: true<br>      selfHeal: true<br>    syncOptions:<br>      - CreateNamespace=true</pre><p>Apply the root app once, then delete your hand-deployed resources; ArgoCD recreates them from Git:</p><pre>kubectl delete ns learning-app<br>kubectl apply -f root-app.yaml</pre><blockquote>Make sure apps/learning-app.yaml is already committed to the gitops repo before applying root-app.yaml. Otherwise the root app will sync successfully but find nothing to deploy.</blockquote><h4><strong>Accessing the ArgoCD UI</strong></h4><pre># Get the initial admin password<br>kubectl -n argocd get secret argocd-initial-admin-secret \<br>  -o jsonpath=&quot;{.data.password}&quot; | base64 -d<br><br># Port-forward the UI<br>kubectl port-forward svc/argocd-server -n argocd 8081:443</pre><p>Open <em>https://localhost:8081</em>, log in as <strong>admin</strong>, and you’ll see the App of Apps tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UA4OjsijEF3V14jLxL0gg.png" /><figcaption>ArgoCD UI showing root-app with the learning-app as a child, both synced (green).</figcaption></figure><h4><strong>Test self-healing</strong></h4><pre># Manually scale to 1 replica<br>kubectl scale deployment learning-app -n learning-app --replicas=1<br><br># Watch ArgoCD revert it back to what Git says<br>kubectl get pods -n learning-app -w</pre><p>Within seconds, ArgoCD notices the drift and restores the desired state. <strong>Git always wins.</strong></p><h3><strong>Step 5: CI/CD Pipeline</strong></h3><p>GitHub Actions builds images and updates the gitops repo automatically.</p><h4><strong>The Flow</strong></h4><pre>You push to learning-app-src<br>        ↓<br>GitHub Actions:<br>  1. Build Docker image<br>  2. Tag with git SHA (e.g., &quot;a4f2b1c&quot;)<br>  3. Push to Docker Hub<br>  4. Clone gitops repo<br>  5. Update values.yaml: tag: &quot;a4f2b1c&quot;<br>  6. Push to gitops repo<br>        ↓<br>ArgoCD detects change → deploys new version</pre><h4><strong>Workflow file (.github/workflows/ci.yaml)</strong></h4><pre>name: Build and Deploy<br><br>on:<br>  push:<br>    branches: [main]<br><br>env:<br>  IMAGE: mahirberkano/learning-app<br><br>jobs:<br>  build-and-push:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Set image tag<br>        id: tag<br>        run: echo &quot;tag=$(git rev-parse --short HEAD)&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br><br>      - name: Login to Docker Hub<br>        uses: docker/login-action@v3<br>        with:<br>          username: ${{ secrets.DOCKERHUB_USERNAME }}<br>          password: ${{ secrets.DOCKERHUB_TOKEN }}<br><br>      - name: Build and push<br>        uses: docker/build-push-action@v5<br>        with:<br>          context: .<br>          push: true<br>          tags: |<br>            ${{ env.IMAGE }}:${{ steps.tag.outputs.tag }}<br>            ${{ env.IMAGE }}:latest<br><br>      - name: Update gitops repo<br>        run: |<br>          git clone https://x-access-token:${{ secrets.GIT_TOKEN }}@github.com/mahirberkano/learning-app-gitops.git<br>          cd learning-app-gitops<br>          sed -i &quot;s|tag: .*|tag: \&quot;${{ steps.tag.outputs.tag }}\&quot;|&quot; charts/learning-app/values.yaml<br>          git config user.name &quot;github-actions&quot;<br>          git config user.email &quot;actions@github.com&quot;<br>          git commit -am &quot;ci: bump image to ${{ steps.tag.outputs.tag }}&quot;<br>          git push</pre><blockquote><em>sed</em> works for a learning project but it’s fragile, rewriting every line matching tag: in the file. For anything beyond a demo, use <a href="https://github.com/mikefarah/yq">yq</a> instead:</blockquote><pre>yq -i &#39;.image.tag = &quot;${{ steps.tag.outputs.tag }}&quot;&#39; charts/learning-app/values.yaml</pre><h4><strong>Required secrets</strong></h4><ul><li><strong>DOCKERHUB_USERNAME:</strong> Docker Hub login</li><li><strong>DOCKERHUB_TOKEN:</strong> Docker Hub access token (read/write)</li><li><strong>GIT_TOKEN:</strong> GitHub PAT with <em>repo</em> scope (push to gitops repo)</li></ul><h3><strong>Step 6: HPA (Horizontal Pod Autoscaler)</strong></h3><p>HPA automatically scales pod count based on CPU (or memory, or custom metrics).</p><h4><strong>How it works</strong></h4><p>Every 15 seconds, HPA calculates:</p><p>desiredReplicas = ceil(currentReplicas × (currentMetric / targetMetric))</p><p>Example: 2 pods at 120% CPU, target 50%:</p><p>ceil(2 × 120/50) = ceil(4.8) = 5 pods</p><h4><strong>Prerequisites</strong></h4><pre>minikube addons enable metrics-server<br># Verify:<br>kubectl top pods -n learning-app</pre><h4><strong>HPA manifest</strong></h4><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: learning-app<br>  namespace: learning-app<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: learning-app<br>  minReplicas: 2<br>  maxReplicas: 10<br>  metrics:<br>    - type: Resource<br>      resource:<br>        name: cpu<br>        target:<br>          type: Utilization<br>          averageUtilization: 50<br>  behavior:<br>    scaleDown:<br>      stabilizationWindowSeconds: 60</pre><h4>Load test</h4><pre># Terminal 1: port-forward the service<br>kubectl port-forward svc/learning-app -n learning-app 8080:80<br><br># Terminal 2: watch HPA in real time<br>kubectl get hpa -n learning-app -w<br><br># Terminal 3: generate load (burns CPU for 30 seconds)<br>curl &quot;http://localhost:8080/load?duration=30s&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcT_mx6c-ZkqF_IoU0UwQA.png" /><figcaption>The /ui/ dashboard with the load generator button.</figcaption></figure><p><strong>What you’ll observe:</strong></p><ol><li>CPU % climbs above 50%</li><li>HPA scales replicas up (toward max 10)</li><li>Load finishes → CPU drops</li><li>After 60 seconds of low usage → scales back to 2</li></ol><h4><strong>Why resource requests matter</strong></h4><p>HPA calculates utilization as actual_cpu / requests.cpu. Without requests defined, HPA can’t compute a percentage and won’t scale. This is the most common HPA “it’s not working” issue.</p><h3><strong>Karpenter: Node-Level Autoscaling (AWS EKS)</strong></h3><blockquote><strong>Note:</strong> Karpenter requires an AWS EKS cluster. It cannot run on minikube. This section is conceptual.</blockquote><h4><strong>The Problem HPA Can’t Solve</strong></h4><p>HPA adds pods, but what if there are no nodes with enough capacity to schedule them? The new pods stay Pending. You need something to add <strong>nodes</strong>.</p><h4><strong>What Karpenter Does</strong></h4><p>Karpenter is an AWS-native node autoscaler that provisions right-sized EC2 instances when pods can’t be scheduled.</p><pre>Pod unschedulable (no node capacity)<br>        ↓<br>Karpenter reads pod requirements (CPU, memory, GPU, topology)<br>        ↓<br>Calls EC2 CreateFleet API → provisions optimal instance<br>        ↓<br>Node registers → pod gets scheduled</pre><h4><strong>Karpenter vs Cluster Autoscaler</strong></h4><ul><li><strong>How it works: </strong>Cluster Autoscaler: Scales existing node groups (ASGs) · Karpenter: Provisions individual instances directly</li><li><strong>Instance selection:</strong> Cluster Autoscaler: Limited to what’s in the node group · Karpenter: Picks from entire EC2 catalog dynamically</li><li><strong>Speed: </strong>Cluster Autoscaler: Minutes (ASG scaling) · Karpenter: Seconds (direct EC2 API)</li><li><strong>Right-sizing: </strong>Cluster Autoscaler: One size fits all in a node group · Karpenter: Picks exact instance for the workload</li><li><strong>Consolidation: </strong>Cluster Autoscaler: None · Karpenter: Actively moves pods to fewer nodes</li><li><strong>Spot: </strong>Cluster Autoscaler: Mixed-instance ASG policies · Karpenter: Native interruption handling + automatic fleet diversification</li></ul><h4><strong>Key Concepts</strong></h4><p><strong>NodePool</strong>: defines constraints for provisioned nodes:</p><pre>apiVersion: karpenter.sh/v1<br>kind: NodePool<br>spec:<br>  template:<br>    spec:<br>      requirements:<br>        - key: karpenter.sh/capacity-type<br>          operator: In<br>          values: [&quot;on-demand&quot;, &quot;spot&quot;]<br>        - key: node.kubernetes.io/instance-type<br>          operator: In<br>          values: [&quot;m5.large&quot;, &quot;m5.xlarge&quot;, &quot;c5.large&quot;, &quot;c5.xlarge&quot;]<br>  disruption:<br>    consolidationPolicy: WhenEmptyOrUnderutilized</pre><p><strong>EC2NodeClass</strong>: AWS-specific configuration:</p><pre>apiVersion: karpenter.k8s.aws/v1<br>kind: EC2NodeClass<br>spec:<br>  amiSelectorTerms:<br>    - alias: al2023@latest<br>  subnetSelectorTerms:<br>    - tags:<br>        karpenter.sh/discovery: my-cluster<br>  securityGroupSelectorTerms:<br>    - tags:<br>        karpenter.sh/discovery: my-cluster</pre><p><strong>Consolidation</strong>: Karpenter continuously evaluates:</p><ul><li>Can this expensive on-demand node be replaced with a cheaper spot instance?</li><li>Can pods on an underutilized node fit elsewhere so we terminate it?</li><li>Are there empty nodes we can remove?</li></ul><p>This runs continuously, saving significant cloud costs without manual intervention.</p><h4><strong>When to Use Karpenter vs Cluster Autoscaler</strong></h4><ul><li><strong>Use Karpenter</strong> if you’re on EKS and want fast, cost-efficient, intelligent scaling</li><li><strong>Use Cluster Autoscaler</strong> if you’re on GKE/AKS or need simpler node group management</li><li><strong>Use neither</strong> if your workload is stable and you can pre-provision nodes</li></ul><h4><strong>The Full Scaling Picture</strong></h4><pre>Traffic increases<br>        ↓<br>HPA: &quot;CPU is high, I need more pods&quot;<br>        ↓<br>HPA creates new pods → some are Pending (no capacity)<br>        ↓<br>Karpenter: &quot;Pods need 2 CPU + 4GB, let me find the cheapest instance&quot;<br>        ↓<br>Provisions c5.large spot instance in 30 seconds<br>        ↓<br>Pods scheduled → traffic served<br>        ↓<br>Traffic decreases<br>        ↓<br>HPA scales down pods → node becomes underutilized<br>        ↓<br>Karpenter consolidation: &quot;This node is 20% used, moving pods elsewhere&quot;<br>        ↓<br>Node terminated → cost saved</pre><h4><strong>The Path Forward (When You Have an AWS Account)</strong></h4><p>If you want to take this learning project to EKS and try Karpenter for real, the rough steps are:</p><pre># 1. Create a small EKS cluster (use eksctl for the quickest path)<br>eksctl create cluster --name karpenter-demo \<br>  --region eu-central-1 \<br>  --node-type t3.medium \<br>  --nodes 2<br><br># 2. Install Karpenter via Helm<br>helm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter \<br>  --version &quot;1.0.0&quot; \<br>  --namespace kube-system \<br>  --create-namespace \<br>  --set &quot;settings.clusterName=karpenter-demo&quot; \<br>  --wait<br><br># 3. Apply your NodePool and EC2NodeClass (the YAMLs shown above)<br>kubectl apply -f nodepool.yaml<br>kubectl apply -f ec2nodeclass.yaml<br><br># 4. Point the same ArgoCD setup at this cluster<br># 5. Hammer the /load endpoint hard enough that HPA exhausts node capacity<br># 6. Watch Karpenter spin up new EC2 instances in real time</pre><p>The IAM setup (Karpenter Controller role, Node IAM role, instance profile, SQS interruption queue) is the only fiddly part: follow the <a href="https://karpenter.sh/docs/getting-started/">official Karpenter getting-started guide</a> which gives you the CloudFormation template that creates everything in one shot.</p><blockquote><strong>Cost warning:</strong> a t3.medium EKS cluster runs ~$0.10/hour for the control plane + ~$0.04/hour per node. If you tear down the cluster the same day you create it, the whole experiment costs less than a coffee. Just don’t forget the eksctl delete cluster at the end.</blockquote><h3><strong>Key Takeaways</strong></h3><ol><li><strong>Separation of concerns</strong>: source code and infrastructure live in separate repos</li><li><strong>Git is the source of truth</strong>: the cluster always matches what’s in Git</li><li><strong>Self-healing</strong>: manual changes are overwritten, forcing everyone through Git</li><li><strong>Declarative &gt; imperative</strong>: you declare desired state, controllers make it happen</li><li><strong>Resource requests matter</strong>: HPA and Karpenter both need accurate resource declarations</li><li><strong>Immutable deploys</strong>: new code = new image tag = new rollout. Never mutate running containers</li><li><strong>Scale at two levels</strong>: HPA scales pods (horizontal), Karpenter scales nodes (infrastructure)</li></ol><h3><strong>Repos</strong></h3><p><a href="https://github.com/mahirberkano/learning-app-src">GitHub - mahirberkano/learning-app-src: Microservice source + CI</a></p><p>Go microservice + CI pipeline</p><p><a href="https://github.com/mahirberkano/learning-app-gitops">GitHub - mahirberkano/learning-app-gitops: K8s manifests + ArgoCD apps</a></p><p>Helm charts + ArgoCD applications</p><p><em>Built on minikube, deployed with ArgoCD, scaled with HPA. The concepts transfer directly to production EKS/GKE clusters — the tools are the same, just the infrastructure gets bigger.</em></p><p><strong>Written by Mahir Berkan Oğuz</strong> — Cloud / DevOps Engineer at <strong>Clerion</strong>, an AWS consulting partner. This is a personal learning project, not client work. Find me on <a href="https://github.com/mahirberkano">GitHub</a> / <a href="https://www.linkedin.com/in/mahirberkanoguz//">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3188a99c7647" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clerion/kubernetes-gitops-from-scratch-a-hands-on-guide-with-argocd-hpa-and-karpenter-3188a99c7647">Kubernetes + GitOps from Scratch: A Hands-On Guide with ArgoCD, HPA, and Karpenter</a> was originally published in <a href="https://medium.com/clerion">Clerion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Chunking Right: The Most Misunderstood Layer in Enterprise RAG]]></title>
            <link>https://medium.com/clerion/getting-chunking-right-the-most-misunderstood-layer-in-enterprise-rag-e3853b65476b?source=rss----4c23810537fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/e3853b65476b</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[enterprise-technology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Batuhan Zorbey Zengin]]></dc:creator>
            <pubDate>Fri, 22 May 2026 08:59:36 GMT</pubDate>
            <atom:updated>2026-05-22T08:59:34.907Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“We split our documents every 500 words, pushed them into a vector database, and it works great.”<em> Most engineers who say this spend the next three months wondering why their system stopped giving useful answers.</em></blockquote><h3>Introduction: Why Is Chunking So Critical?</h3><p>The conversations that dominate RAG architecture planning tend to revolve around the same questions: which LLM should we use, which vector database should we pick, what embedding model makes sense. While these debates continue, the arguably most critical step in the entire pipeline — how documents are split into pieces — gets overlooked.</p><p>Two separate academic studies addressed this question directly, and their findings complement each other.</p><p>Qu et al.’s peer-reviewed paper published in NAACL 2025 Findings (“Is Semantic Chunking Worth the Computational Cost?”, arXiv:2410.13070) systematically evaluated semantic chunking across three tasks: document retrieval, evidence retrieval, and retrieval-based answer generation. The conclusion was clear: <strong>the additional computational cost of semantic chunking is not justified by consistent performance gains.</strong> The assumption that “semantic chunking is always better” has been challenged at the peer-reviewed level.</p><p>A separate domain-specific study comparing 25 chunking configurations against 48 embedding models reached another important conclusion: chunking and embedding model selection must be evaluated together. Optimizing one independently of the other leads to misleading results.</p><p>Think about what that means. You spend months debating which embedding model to use, but the wrong chunking strategy can make that decision entirely irrelevant.</p><p>This article answers the following questions:</p><ul><li>Why do chunking strategies make such a significant difference?</li><li>What do real benchmark data say about each available strategy?</li><li>Why is the “semantic chunking always wins” narrative wrong?</li><li>Which strategy should be chosen for which document type?</li><li>What tools and code examples can be used in production?</li></ul><h3>Section 1: Why Chunking Matters This Much</h3><p>The basic RAG loop goes like this: split the document into chunks, embed each chunk, find the most relevant chunks when a user query arrives, pass them to the LLM as context, generate a response.</p><p>Chunking is the first step in this loop, and it directly affects everything that follows. Your retrieval system can only work with the chunks it has. If a piece of information is split across the wrong chunk boundaries, that information effectively does not exist as far as your system is concerned.</p><p>To make this concrete, consider this paragraph from a corporate finance document:</p><blockquote>“The company’s biggest risk in Q3 2023 was the sudden volatility in exchange rates. This particularly impacted operations in Turkey and Argentina and pulled the EBITDA margin down by 3.2 points.”</blockquote><p>If you split this sentence right down the middle — “This particularly impacted operations in Turkey and Argentina” in one chunk and “and pulled the EBITDA margin down by 3.2 points” in another — the system will try to answer “What affected EBITDA in Q3 2023?” but will be working with disconnected fragments.</p><h3>The Two Opposing Forces of Chunk Size</h3><p>Designing a chunking strategy means constantly wrestling with two opposing forces.</p><p><strong>Small chunks</strong> deliver high retrieval precision — you find exactly what you are looking for. But the context passed to the LLM is thin; the model does not have enough surrounding information to generate a reliable answer.</p><p><strong>Large chunks</strong> give the LLM richer context. But retrieval noise increases; irrelevant information enters the query results and context dilution sets in.</p><p>To put a number on this trade-off: Chroma’s research showed that the recall gap between the best and worst chunking strategy on the same corpus can reach 9%. That may sound small, but in an enterprise system handling 10,000 queries per day, it translates to 900 incorrectly answered questions every single day.</p><h3>Section 2: The Chunking Strategy Catalogue</h3><p>Here is a practical breakdown of each available strategy alongside real-world usage scenarios.</p><h3>2.1 Fixed-Size Chunking</h3><p>The most basic approach. A new chunk starts every N tokens or characters. An optional overlap between chunks can be added to preserve some continuity.</p><pre>import tiktoken<br>from langchain_text_splitters import RecursiveCharacterTextSplitter</pre><pre>enc = tiktoken.encoding_for_model(&quot;text-embedding-3-small&quot;)</pre><pre>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=512,<br>    chunk_overlap=50,<br>    # Do not use length_function=len: it counts characters, not tokens.<br>    # You will get ~100-130 tokens per chunk instead of the intended 512.<br>    length_function=lambda text: len(enc.encode(text)),<br>)<br>chunks = splitter.split_text(document)</pre><p><strong>When it works:</strong> Log files, flat data exports, homogeneous-structure documents. The ideal starting point for baseline tests.</p><p><strong>When it breaks:</strong> Any document type with semantic continuity. It splits sentences mid-thought and cuts paragraphs in half.</p><p><strong>Microsoft Azure’s recommendation:</strong> Start with 512 tokens and 25% overlap (128 tokens) — use real token counts, not character counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xG5yxfiG7JD_tWcf4MtqJQ.png" /></figure><h3>2.2 Recursive Character Text Splitting</h3><p>LangChain’s most widely used splitter. It works through a hierarchical priority list: double newline first, then single newline, then period, then space. If a chunk is still larger than the target size after applying one separator, it moves on to the next.</p><pre>import tiktoken<br>from langchain_text_splitters import RecursiveCharacterTextSplitter</pre><pre>enc = tiktoken.encoding_for_model(&quot;text-embedding-3-small&quot;)</pre><pre>splitter = RecursiveCharacterTextSplitter(<br>    separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot;. &quot;, &quot;? &quot;, &quot;! &quot;, &quot; &quot;, &quot;&quot;],<br>    chunk_size=512,<br>    chunk_overlap=128,<br>    # Counts real tokens, not characters; stays consistent with chunk_size.<br>    length_function=lambda text: len(enc.encode(text)),<br>)</pre><blockquote><em>⚠️ </em><strong><em>Common mistake:</em></strong><em> Using </em><em>length_function=len gives you 512 characters, not 512 tokens — roughly 100 to 130 tokens, far below your target. Token-based length functions keep your chunking consistent with the context window of your embedding model.</em></blockquote><p><strong>Benchmark data:</strong> In Vecta’s February 2026 benchmark study (50 academic papers, 905,746 tokens, equal context budget via adaptive k), recursive 512-token splitting ranked first with 69% accuracy, outperforming semantic chunking by 15 points.</p><p><strong>Important context:</strong> This benchmark ran on academic papers using a single embedding model and generator. As the authors themselves note, results may vary across different document types and different pipeline components. The finding is not “recursive always wins” — it means that <strong>poorly tuned semantic chunking can fall behind recursive splitting</strong>.</p><p><strong>Why it performs so well:</strong> On structured content like academic papers, technical documentation, and reports, it respects paragraph boundaries and produces consistent results.</p><p><strong>When it falls short:</strong> When document structure is weak — free-flowing prose, call transcripts, conversational data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_6p42LgfUkgv2EJopub6w.png" /></figure><h3>2.3 Semantic Chunking</h3><p>The core idea: what should separate chunks is not a token boundary but a shift in meaning. Each sentence is embedded individually, cosine similarity is computed between neighboring sentences, and a new chunk begins whenever similarity drops below a defined threshold.</p><pre>from langchain_experimental.text_splitter import SemanticChunker<br>from langchain_openai.embeddings import OpenAIEmbeddings</pre><pre>semantic_splitter = SemanticChunker(<br>    embeddings=OpenAIEmbeddings(),<br>    breakpoint_threshold_type=&quot;percentile&quot;,<br>    breakpoint_threshold_amount=95,<br>    # Without min_chunk_size, over-fragmentation occurs.<br>    # In Vecta&#39;s benchmark, omitting this parameter produced avg. 43-token chunks.<br>    min_chunk_size=200,<br>)<br>chunks = semantic_splitter.split_text(document)</pre><blockquote><em>💡 </em><strong><em>Over-Fragmentation Trap:</em></strong><em> Skipping </em><em>min_chunk_size is the most common production mistake with semantic chunking. In Vecta&#39;s benchmark, semantic chunking without this parameter (using a 0.7 cosine threshold) produced chunks averaging 43 tokens — high retrieval recall but insufficient context for the LLM, resulting in only 54% end-to-end accuracy. Start with </em><em>min_chunk_size=150 and calibrate against your own document set.</em></blockquote><p><strong>Chroma’s finding:</strong> LLMSemanticChunker achieved 0.919 recall and ClusterSemanticChunker reached 0.913 — both above recursive splitting.</p><p>But here is the critical distinction.</p><p>Chroma’s data measured retrieval recall. Vecta measured end-to-end answer accuracy — meaning “did the LLM produce the correct answer?”</p><p>In Vecta’s benchmark, semantic chunking with a 0.7 cosine threshold produced chunks averaging 43 tokens. Those chunks delivered high page-level recall (0.91), but document-level F1 collapsed to 0.42 and end-to-end accuracy landed at 54% — 15 points behind recursive. The problem is not semantic chunking itself; the problem is that it becomes fragile without threshold tuning, minimum chunk size enforcement, and post-merge heuristics.</p><p><strong>The takeaway:</strong> High retrieval recall does not equal high answer quality. If you use semantic chunking, you must calibrate both min_chunk_size and breakpoint_threshold_amount against your own document set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKgcob5LP74GffPnMZ17og.png" /></figure><h3>2.4 Parent-Child (Hierarchical) Chunking</h3><p>This strategy addresses two problems simultaneously: retrieval precision and context richness.</p><p>The mechanics work as follows:</p><ol><li>Create <strong>parent chunks</strong> — large, context-rich segments (500–2000 tokens), typically a section or several paragraphs.</li><li>Create <strong>child chunks</strong> — small, focused pieces (100–500 tokens), derived from within each parent.</li><li>During retrieval, <strong>child chunks</strong> are searched — high precision.</li><li>When a child is found, its corresponding <strong>parent chunk</strong> is passed to the LLM — rich context.</li></ol><pre>from langchain.retrievers import ParentDocumentRetriever<br>from langchain.storage import InMemoryStore<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain_community.vectorstores import Chroma</pre><pre>parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000)<br>child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)</pre><pre>vectorstore = Chroma(embedding_function=embeddings)<br>store = InMemoryStore()</pre><pre>retriever = ParentDocumentRetriever(<br>    vectorstore=vectorstore,<br>    docstore=store,<br>    child_splitter=child_splitter,<br>    parent_splitter=parent_splitter,<br>)</pre><p><strong>When to use it:</strong> Technical documentation, API references, academic content with heavy cross-referencing. In the classic “pronoun and cross-reference problem” — where “this system” in chunk 47 refers to something defined in chunk 2 — parent-child preserves semantic coherence.</p><p><strong>Drawback:</strong> Storage cost increases since both parent and child chunks must be stored. Determining optimal chunk sizes requires experimentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSreQdNXhSl8k9SCi1vcWw.png" /></figure><h3>2.5 Late Chunking: A Paradigm Shift</h3><p>Jina AI’s 2024 paper “Late Chunking: Contextual Chunk Embeddings Using Long-Context Embedding Models” (arXiv:2409.04701) fundamentally challenged the conventional approach to chunking.</p><p>The standard sequence is: <strong>split first, then embed.</strong></p><p>Late chunking reverses this: <strong>embed first, then split.</strong></p><p>Specifically, the entire document is fed to a long-context embedding model and encoded at the token level. Chunking is then applied after the transformer but <em>before</em> mean pooling. This means each chunk embedding carries contextual information from the rest of the document.</p><pre>from chonkie import LateChunker</pre><pre>chunker = LateChunker(<br>    embedding_model=&quot;jinaai/jina-embeddings-v2-base-en&quot;,<br>    chunk_size=512,<br>)<br>chunks = chunker(&quot;Your long document text here...&quot;)</pre><pre># Each chunk contains both text and a contextual embedding<br>for chunk in chunks:<br>    print(chunk.text)<br>    print(chunk.embedding)  # Contextual embedding derived from the full document</pre><p><strong>Why it matters:</strong> Phrases like “the system” or “this situation” lose their referent in standard chunking. In late chunking, these phrases carry their original context at the embedding level.</p><blockquote><em>⚠️ </em><strong><em>Critical API Constraint:</em></strong><em> Late chunking does not work with every embedding provider. Closed APIs like OpenAI (</em><em>text-embedding-3) or Cohere return a single pooled vector rather than token-level embeddings from the transformer. For late chunking to work, the model must expose token-level embeddings before mean pooling. This requires either Jina AI&#39;s own API (</em><em>jinaai/jina-embeddings-v2-base-en) or an open-source model like </em><em>nomic-embed-text hosted on your own infrastructure.</em></blockquote><p><strong>An important comparison:</strong> Research suggests contextual retrieval better preserves semantic coherence, while late chunking is more computationally efficient but may make concessions on relevance and completeness in some scenarios. It is not a silver bullet — but it is powerful in the right use case.</p><h3>2.6 Agentic / LLM-Powered Chunking</h3><p>The most expensive and, when done well, the highest-quality approach. You show a document to an LLM and ask it to split the text into semantically meaningful pieces. The model analyzes the document’s structure, density, and content before making dynamic boundary decisions.</p><pre>from chonkie import SlumberChunker</pre><pre># Chonkie is an actively developed library; API names may change.<br># If SlumberChunker is not found, try these alternatives:<br># from chonkie import LLMChunker<br># from chonkie import AgenticChunker<br># For the current API, see: <a href="https://github.com/chonkie-inc/chonkie">https://github.com/chonkie-inc/chonkie</a></pre><pre>chunker = SlumberChunker(<br>    model=&quot;gpt-4o-mini&quot;,<br>    chunk_size=512,<br>    min_characters_per_chunk=100,<br>)<br>chunks = chunker(long_document)</pre><p><strong>When it earns its cost:</strong> High-stakes content like medical and legal documents. A clinical decision support study published in MDPI Bioengineering (November 2025) found that an <strong>adaptive chunking</strong> pipeline raised the rate of “at least somewhat accurate” answers on post-rhinoplasty clinical questions to 87%, compared to 50% for the fixed-size baseline. For “completely accurate” answers, adaptive reached 50% versus 13% for baseline. The study was limited to 30 questions, but the signal is clear: adaptive boundary policy directly affects clinical accuracy.</p><blockquote><strong><em>Terminology note:</em></strong><em> This strategy appears in the literature as “agentic,” “adaptive,” or “LLM-powered” chunking. The MDPI study’s method is technically </em>adaptive chunking<em> — it uses embedding similarity and dynamic window sizing, not a per-chunk LLM call. True agentic chunking (an LLM call per chunk) is considerably more expensive.</em></blockquote><p><strong>When to avoid it:</strong> Large-scale enterprise archives with millions of pages. The cost of an LLM call per document compounds rapidly at scale. Estimated cost for 50,000 documents: approximately $1,150 as a one-time ingestion expense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-SK2A5GnDuczbBBLvB0zcQ.png" /></figure><h3>Section 3: Benchmark Reality Check</h3><p>Here is a consolidated view of the data across all strategies:</p><p>Strategy Vecta 2026 Accuracy Chroma Recall NVIDIA (Paged) Cost Best For Recursive (512t) <strong>69%</strong> ✅ 85–89% — Low General purpose Semantic (embedding) 54% ⚠️ 91–93% — Medium Multi-topic content Page-Level — — <strong>0.648</strong> ✅ Low Financial PDFs Parent-Child — — — Medium Technical docs Late Chunking — — — Medium Heavy cross-reference content Agentic — — — <strong>High</strong> Medical / legal</p><p><strong>What the table tells you:</strong> There is no single best strategy. The right question is not “semantic or recursive?” but rather “which document type, which query pattern, which budget?”</p><h3>Section 4: How to Choose Your Strategy — A Decision Framework</h3><p>Work through the following questions in order.</p><h3>Step 1: What is the structure of your documents?</h3><ul><li><strong>Paginated, structured PDFs (financial reports, academic papers, legal contracts):</strong> Try page-level chunking. NVIDIA’s data shows this delivers the most consistent results for this document type.</li><li><strong>Markdown, technical documentation, API references:</strong> Recursive character splitter — headings and paragraphs create natural boundaries.</li><li><strong>Free-flowing prose, reports, research:</strong> Parent-child combination.</li><li><strong>Conversations, transcripts, multi-topic content:</strong> Semantic chunking — but enforce a minimum chunk size (150+ tokens).</li><li><strong>Medical records, legal text, high-stakes content:</strong> Agentic chunking if the cost can be justified.</li></ul><h3>Step 2: What type of queries will your users run?</h3><ul><li><strong>Factoid queries</strong> (“What is X?”, “When was Y?”): Small chunks in the 256–512 token range — high precision.</li><li><strong>Analytical queries</strong> (“What was the biggest risk in Q3 2023 and why?”): 1024+ tokens — the LLM needs more context.</li><li><strong>Complex, multi-step queries:</strong> Parent-child or late chunking.</li></ul><h3>Step 3: What is your scale?</h3><ul><li><strong>Under 10,000 documents:</strong> Semantic or agentic chunking is cost-reasonable.</li><li><strong>10,000 to 1,000,000 documents:</strong> Recursive or page-level — cost and speed are critical.</li><li><strong>Over 1,000,000 documents:</strong> Start with a fixed-size baseline; apply a differentiated strategy only for critical document segments.</li></ul><h3>Step 4: Always measure</h3><p>Chunking strategy is not a set-and-forget decision. Track these metrics in every production system:</p><ul><li><strong>Retrieval Recall:</strong> Is the needed information present in the top-k results?</li><li><strong>Answer Accuracy:</strong> Did the LLM produce the correct answer? (Different from retrieval recall — recall the Vecta benchmark finding.)</li><li><strong>Chunk size distribution:</strong> Is your average chunk size 43 tokens? That is a problem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_loPEbEXaMKf_8YOsoSkg.png" /></figure><h3>Section 5: Techniques That Strengthen Any Chunking Strategy</h3><p>Beyond strategy selection, several techniques can meaningfully improve the output of any approach.</p><h3>5.1 Metadata Enrichment</h3><p>A chunk does not have to be raw text. You can pass each chunk to an LLM and ask it to generate structured metadata:</p><pre>def enrich_chunk_with_metadata(chunk_text, llm):<br>    prompt = f&quot;&quot;&quot;<br>    Analyze the following text passage and generate metadata in JSON format:<br>    <br>    Text: {chunk_text}<br>    <br>    Fill in these fields:<br>    - topic_category: (e.g., &quot;Financial Risk&quot;, &quot;Operational Performance&quot;)<br>    - time_period: (e.g., &quot;Q3 2023&quot;, &quot;FY2024&quot;, can be empty)<br>    - document_type: (e.g., &quot;Annual Report&quot;, &quot;Internal Policy&quot;)<br>    - key_entities: (company names, people, locations)<br>    &quot;&quot;&quot;<br>    return llm.invoke(prompt)</pre><p>This lets you combine pure vector search with metadata filtering. A query for “Q3 2023 risk” can now be answered using both semantic similarity and a time-range filter.</p><h3>5.2 Contextual Chunk Headers</h3><p>Prepend high-level document context to each chunk:</p><pre>def add_context_header(chunk_text, document_summary, section_title):<br>    header = f&quot;&quot;&quot;[Document: {document_summary}]<br>[Section: {section_title}]</pre><pre>&quot;&quot;&quot;<br>    return header + chunk_text</pre><p>This approach appears in LangChain’s semantic chunker documentation as “contextual embedding.” When chunk 47 contains a phrase like “this system,” the embedding model can now understand which system it refers to, because the header carries that context.</p><h3>5.3 Adaptive Chunk Sizing</h3><p>Rather than fixing a single chunk size, use dynamic sizing based on document density:</p><pre>from chonkie import Pipeline</pre><pre>pipe = (<br>    Pipeline()<br>    .chunk_with(&quot;recursive&quot;, tokenizer=&quot;gpt2&quot;, chunk_size=2048, recipe=&quot;markdown&quot;)<br>    .chunk_with(&quot;semantic&quot;, chunk_size=512)<br>    .refine_with(&quot;overlap&quot;, context_size=128)<br>    .refine_with(&quot;embeddings&quot;, embedding_model=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br>)</pre><h3>Section 6: Tools You Can Use in Production</h3><h3>Chonkie — Recommended Starting Point</h3><p>Lightweight, fast, production-ready. Supports 32+ integrations and 56 languages.</p><pre>pip install chonkie[semantic]</pre><p>Available chunkers: TokenChunker, SentenceChunker, RecursiveChunker, SemanticChunker, SDPMChunker, LateChunker, CodeChunker, NeuralChunker, SlumberChunker (Agentic).</p><p>→ <a href="https://github.com/chonkie-inc/chonkie">https://github.com/chonkie-inc/chonkie</a></p><h3>semchunk — Proven in Production</h3><p>Used in Docling and the Microsoft Intelligence Toolkit. Claims 15% better RAG performance than its closest competitor.</p><pre>pip install semchunk</pre><p>→ <a href="https://github.com/isaacus-dev/semchunk">https://github.com/isaacus-dev/semchunk</a></p><h3>NVIDIA RAG Blueprint</h3><p>Enterprise-scale reference implementation with NeMo Retriever Reranker integration included.</p><p>→ <a href="https://github.com/NVIDIA-AI-Blueprints/rag">https://github.com/NVIDIA-AI-Blueprints/rag</a></p><h3>NVIDIA Context-Aware RAG</h3><p>For context-aware retrieval with Knowledge Graph support.</p><p>→ <a href="https://github.com/NVIDIA/context-aware-rag">https://github.com/NVIDIA/context-aware-rag</a></p><h3>FuzzyLabs — Comparison Notebook</h3><p>A Jupyter notebook comparing fixed-size vs. semantic chunking and the impact of reranking from scratch.</p><p>→ <a href="https://github.com/fuzzylabs/innovation-rag-semantic-chunking">https://github.com/fuzzylabs/innovation-rag-semantic-chunking</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QV24Xr3cg6CrmLI1DxAdcg.png" /></figure><h3>Section 7: Enterprise-Grade Chunking Architecture on AWS</h3><p>You do not have to build everything from scratch on your own servers. AWS offers most of this architecture as managed services. But “managed” does not mean configuration decisions are made for you — matching the right service to the right strategy still requires engineering judgment.</p><p>Here is a layer-by-layer breakdown of how an enterprise RAG architecture can be structured on AWS.</p><h3>Architecture Overview</h3><pre>[Data Sources]          [Processing Layer]           [Storage &amp; Retrieval]       [Response Generation]<br>S3 / SharePoint    →    Bedrock Knowledge Bases   →   OpenSearch Serverless   →   Bedrock LLM<br>Confluence              (Chunking + Embedding)         Aurora PostgreSQL           (Claude / Titan)<br>Salesforce                       ↓                     Neptune Analytics<br>Web Crawler              Lambda (Custom Logic)          (GraphRAG)</pre><h3>Layer 1 — Data Source and Ingestion (S3 + Bedrock KB)</h3><p>Everything starts with an upload to S3. Bedrock Knowledge Bases supports incremental sync for S3 data sources, but files added or removed from S3 do <strong>not</strong> automatically reflect in the index. Triggering sync requires either initiating it from the AWS Management Console or making a StartIngestionJob API call. For automated sync in production, it is recommended to build an event-driven pipeline using EventBridge and Lambda or S3 event notifications. Beyond S3, pre-built connectors are available for Confluence, Salesforce, SharePoint, and web crawlers.</p><p><strong>Critical point:</strong> The chunking strategy is selected during ingestion and cannot be changed afterward. Getting this decision right from the start is mandatory.</p><h3>Layer 2 — Chunking Strategy Selection (Bedrock KB Console)</h3><p>Bedrock Knowledge Bases exposes the strategies covered in this article directly through the console:</p><p>Bedrock KB Option Equivalent in This Article When to Choose Fixed Size Fixed-size chunking Homogeneous content, baseline testing Default Recursive (AWS optimized) General-purpose starting point Semantic Semantic chunking Multi-topic, free-flowing text Hierarchical Parent-child chunking Technical documentation, cross-references Custom (Lambda) Agentic / custom logic Domain-specific requirements</p><p>If you manage infrastructure with Terraform, the semantic chunking configuration looks like this:</p><pre>variable &quot;semantic_max_tokens&quot; {<br>  default = 512<br>}</pre><pre>variable &quot;semantic_breakpoint_percentile_threshold&quot; {<br>  default = 75  # Threshold for detecting meaning shifts<br>}</pre><pre>variable &quot;semantic_buffer_size&quot; {<br>  default = 1   # Number of neighboring sentences for context window<br>}</pre><p>The breakpoint_percentile_threshold value is critical: a lower value produces smaller, more precise chunks; a higher value produces larger, more contextual ones. Connect this back to Vecta&#39;s benchmark finding: very small chunks (averaging 43 tokens at a 0.7 threshold) deliver high retrieval recall but provide insufficient context to the LLM.</p><h3>Layer 3 — Custom Chunking: Full Control with Lambda</h3><p>When standard options are not enough — for example, you have a domain-specific legal contract format or need to attach automatic metadata to each chunk — Lambda is the answer.</p><pre># lambda_function.py — custom chunker connected to Bedrock KB<br>import json<br>import boto3</pre><pre>def lambda_handler(event, context):<br>    s3 = boto3.client(&#39;s3&#39;)<br>    input_files = event.get(&#39;inputFiles&#39;)<br>    input_bucket = event.get(&#39;bucketName&#39;)<br>    output_files = []</pre><pre>    for input_file in input_files:<br>        for batch in input_file.get(&#39;contentBatches&#39;, []):<br>            # Read content from S3<br>            obj = s3.get_object(Bucket=input_bucket, Key=batch[&#39;key&#39;])<br>            text = obj[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)</pre><pre>            # Apply your own chunking logic here<br>            # For example, use Chonkie or semchunk<br>            chunks = your_semantic_chunker(text)</pre><pre>            # Attach metadata to each chunk<br>            enriched_chunks = [<br>                {<br>                    &quot;content&quot;: chunk,<br>                    &quot;metadata&quot;: {<br>                        &quot;source_type&quot;: &quot;legal_contract&quot;,<br>                        &quot;chunk_quality_score&quot;: compute_quality(chunk)<br>                    }<br>                }<br>                for chunk in chunks<br>            ]</pre><pre>            output_files.append({&quot;chunks&quot;: enriched_chunks})</pre><pre>    return {&quot;outputFiles&quot;: output_files}</pre><p><strong>Important IAM note:</strong> A resource-based policy is required for Lambda to be invokable by Bedrock. This is added automatically when you create the Knowledge Base through the console; if you are deploying manually with Terraform, you must define it explicitly.</p><h3>Layer 4 — Vector Store Selection</h3><p>The right vector store depends on your scale and requirements.</p><p><strong>Amazon OpenSearch Serverless</strong> is the recommended starting point for most enterprise use cases. It supports hybrid search (BM25 + vector), which directly addresses the “vector search alone is not enough” problem covered in this article. It scales automatically and requires no server management.</p><p><strong>Amazon OpenSearch Managed Cluster</strong> is for larger workloads and binary vector support, where you want direct control over capacity.</p><p><strong>Amazon Aurora PostgreSQL</strong> suits hybrid scenarios where vector and relational data need to live in the same system. It offers the most flexibility for metadata filtering.</p><p><strong>Amazon S3 Vectors</strong> (GA December 2025) is the lowest-cost option. But read this carefully before choosing it:</p><blockquote><em>🚨 </em><strong><em>Critical Architecture Trap:</em></strong><em> S3 Vectors does not support hybrid search (BM25 + vector) — it supports semantic search only. The decision to go with “S3 Vectors is cheap, let’s drop OpenSearch” leads to this in production: the system becomes blind on queries that require exact matches — product codes, contract numbers, employee IDs, SKUs. Vectors understand meaning, not exact keywords. If your users will run queries like “retrieve clause 5 of contract HR-2024–0047,” hybrid search is mandatory — and in that scenario, S3 Vectors is the wrong choice.</em></blockquote><p>For small-scale or cost-constrained scenarios where pure semantic search is sufficient, it is a reasonable option.</p><p><strong>Amazon Neptune Analytics</strong> is covered in the next layer.</p><h3>Layer 5 — GraphRAG: Automatically Mapping Relationships Between Chunks</h3><p>Earlier in this article, the “Knowledge Graph” layer was mentioned — the need to connect entities across different documents in enterprise systems. AWS made this layer generally available in March 2025 through Neptune Analytics with GraphRAG.</p><p>How it works: Documents are uploaded to S3, Bedrock KB uses a foundation model (Claude 3 Haiku is recommended) to extract entities and relationships from each chunk, and these are automatically written to Neptune Analytics as a graph. At query time, semantic search first identifies the most relevant chunks, then graph traversal pulls in neighboring nodes, delivering richer context to the LLM.</p><p><strong>When GraphRAG earns its cost:</strong> Queries like “Which engineers have worked on which projects?”, “What contracts have we had with this company and which departments were affected?” — anything requiring entity relationships that span multiple documents.</p><p><strong>Cost note:</strong> Neptune Analytics is billed hourly (approximately $0.48/hour). Remember to clean up resources during periods of inactivity.</p><h3>Layer 6 — Hybrid Search and Reranking</h3><p>The combination of vector search and keyword search (hybrid search) is supported only in OpenSearch Serverless, Aurora PostgreSQL, and MongoDB vector store configurations. As noted above, S3 Vectors supports only semantic search — keep this requirement in mind when selecting your vector store.</p><p>For reranking, Bedrock Knowledge Bases offers options like the Cohere Rerank model. A reranker re-scores the initial retrieval results and orders the context passed to the LLM by relevance quality — one of the most practical solutions to the “Lost in the Middle” problem discussed earlier in this article.</p><h3>Recommended Architectural Decisions for Enterprise Scale</h3><p>Putting all these layers together, here is the recommended approach by scale.</p><p><strong>Starter configuration (under 100K documents):</strong></p><ul><li>Chunking: Bedrock KB Hierarchical (parent-child)</li><li>Vector store: OpenSearch Serverless (for hybrid search)</li><li>Embedding: Amazon Titan Text Embeddings v2</li><li>Reranking: Enabled — Cohere Rerank</li></ul><p><strong>Advanced configuration (100K+ documents or cross-document reasoning):</strong></p><ul><li>Chunking: Custom Lambda with domain-specific logic and automatic metadata enrichment</li><li>Vector store: OpenSearch Managed Cluster or Aurora PostgreSQL</li><li>GraphRAG: Neptune Analytics (if entity relationship queries are required)</li><li>Monitoring: CloudWatch for chunk quality scores and query latency tracking</li></ul><p><strong>Operationally critical:</strong> In Bedrock KB, the chunking strategy is set when the data source is created and cannot be changed afterward. Changing strategies requires recreating the data source and re-indexing all documents. Running a benchmark on a small document set before going to production prevents re-indexing work that could otherwise take months.</p><h3>Conclusion: The Right Question</h3><p>In my earlier writing I talked about the “Blind Chunking Disaster.” Before closing this piece, I want to make one thing clear.</p><p>The real problem is not whether you use semantic chunking or avoid it. The real problem is <strong>making the choice without measuring anything.</strong></p><p>In Vecta’s benchmark, semantic chunking fell 15 points behind recursive because of a poorly tuned threshold. But that same semantic chunking outperforms recursive with the right min_chunk_size and breakpoint_threshold_amount configuration applied to the right document type. NVIDIA&#39;s page-level finding is invaluable for paginated PDFs — but it fails on documents where page boundaries are arbitrarily drawn.</p><p>Real engineering starts with asking: <strong>“How does this strategy perform against this document type, for this query pattern?”</strong></p><p>Chunking is not a configuration setting. It is an engineering decision. And like every engineering decision, it must be grounded in data.</p><h3>References</h3><ol><li>Qu, R., Tu, R., &amp; Bao, F. (2025). <em>Is Semantic Chunking Worth the Computational Cost?</em> NAACL 2025 Findings. <a href="https://aclanthology.org/2025.findings-naacl.114/">https://aclanthology.org/2025.findings-naacl.114/</a></li><li>Günther, M., et al. (2024). <em>Late Chunking: Contextual Chunk Embeddings Using Long-Context Embedding Models.</em> arXiv:2409.04701. <a href="https://arxiv.org/abs/2409.04701">https://arxiv.org/abs/2409.04701</a></li><li>Kiss, C., Nagy, M., &amp; Szilágyi, P. (2025). <em>Max–Min Semantic Chunking of Documents for RAG Application.</em> Discover Computing. <a href="https://doi.org/10.1007/s10791-025-09638-7">https://doi.org/10.1007/s10791-025-09638-7</a></li><li>Alberts, I.L., et al. (2025). <em>Chunk Twice, Embed Once: A Systematic Study of Segmentation and Representation Trade-offs in Chemistry-Aware Retrieval-Augmented Generation.</em> arXiv:2506.17277. <a href="https://arxiv.org/abs/2506.17277">https://arxiv.org/abs/2506.17277</a></li><li>Gomez-Cabello, C.A., et al. (2025). <em>Comparative Evaluation of Advanced Chunking for RAG in LLMs for Clinical Decision Support.</em> MDPI Bioengineering. <a href="https://doi.org/10.3390/bioengineering12111194">https://doi.org/10.3390/bioengineering12111194</a></li><li>Vecta Team. (2026). <em>We Benchmarked 7 Chunking Strategies on Real-World Data.</em> <a href="https://www.runvecta.com/blog/we-benchmarked-7-chunking-strategies-most-advice-was-wrong">https://www.runvecta.com/blog/we-benchmarked-7-chunking-strategies-most-advice-was-wrong</a></li><li>NVIDIA Technical Blog. (June 18, 2025). <em>Finding the Best Chunking Strategy for Accurate AI Responses.</em> <a href="https://developer.nvidia.com/blog/finding-the-best-chunking-strategy-for-accurate-ai-responses/">https://developer.nvidia.com/blog/finding-the-best-chunking-strategy-for-accurate-ai-responses/</a></li><li>NVIDIA AI Blueprints RAG. <a href="https://github.com/NVIDIA-AI-Blueprints/rag">https://github.com/NVIDIA-AI-Blueprints/rag</a></li><li>Chonkie Documentation. <a href="https://github.com/chonkie-inc/chonkie">https://github.com/chonkie-inc/chonkie</a></li><li>FuzzyLabs Semantic Chunking Comparison. <a href="https://github.com/fuzzylabs/innovation-rag-semantic-chunking">https://github.com/fuzzylabs/innovation-rag-semantic-chunking</a></li><li>Latif, S., et al. (2025). <em>The Chunking Paradigm: Recursive Semantic for RAG Optimization.</em> ICNLSP 2025. <a href="https://aclanthology.org/2025.icnlsp-1.15.pdf">https://aclanthology.org/2025.icnlsp-1.15.pdf</a></li><li>AWS. (2025). <em>Ingest Changes Directly into a Knowledge Base — Amazon Bedrock Documentation.</em> <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-direct-ingestion.html">https://docs.aws.amazon.com/bedrock/latest/userguide/kb-direct-ingestion.html</a></li><li>AWS. (2025). <em>Using S3 Vectors with Amazon Bedrock Knowledge Bases — Amazon S3 Documentation.</em> <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-bedrock-kb.html">https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-bedrock-kb.html</a></li><li>AWS. (2025). <em>Announcing General Availability of Amazon Bedrock Knowledge Bases GraphRAG with Amazon Neptune Analytics.</em> <a href="https://aws.amazon.com/blogs/machine-learning/announcing-general-availability-of-amazon-bedrock-knowledge-bases-graphrag-with-amazon-neptune-analytics/">https://aws.amazon.com/blogs/machine-learning/announcing-general-availability-of-amazon-bedrock-knowledge-bases-graphrag-with-amazon-neptune-analytics/</a></li><li>AWS Samples. <em>Amazon Bedrock Knowledge Bases — Advanced Chunking Options Notebook.</em> <a href="https://github.com/aws-samples/amazon-bedrock-samples/blob/main/rag/knowledge-bases/features-examples/03-optimizing-accuracy-retrieved-results/advanced_chunking_options.ipynb">https://github.com/aws-samples/amazon-bedrock-samples/blob/main/rag/knowledge-bases/features-examples/03-optimizing-accuracy-retrieved-results/advanced_chunking_options.ipynb</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3853b65476b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clerion/getting-chunking-right-the-most-misunderstood-layer-in-enterprise-rag-e3853b65476b">Getting Chunking Right: The Most Misunderstood Layer in Enterprise RAG</a> was originally published in <a href="https://medium.com/clerion">Clerion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Photo Archive App with Next.js and AWS Amplify Gen 2]]></title>
            <link>https://medium.com/clerion/building-a-photo-archive-app-with-next-js-and-aws-amplify-gen-2-90890c4c0668?source=rss----4c23810537fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/90890c4c0668</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[amplify]]></category>
            <dc:creator><![CDATA[Mahir Berkan Oğuz]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 09:03:40 GMT</pubDate>
            <atom:updated>2025-09-10T14:01:10.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_R8g0afS1sPGIbqbS1b3Q.jpeg" /></figure><p>In this blog post, I’ll walk you through creating a modern photo archive application using Next.js and AWS Amplify Gen 2. This Instagram-like photo app demonstrates how to build a full-stack application with authentication, file and data storage, and scalable cloud deployment using AWS services with Amplify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pjWpQE6l8S-6xHmY76PwA.png" /><figcaption>Diagram for AWS Services</figcaption></figure><h3>What We’re Building</h3><p>Our photo archive app is a modern web application that allows users to:</p><ul><li>Upload and manage photos securely</li><li>View their photo collection in an organized interface</li><li>Authenticate users with AWS Cognito</li><li>Store images in AWS S3 with automatic scaling</li><li>Store data in AWS DynamoDB.</li></ul><p>The complete project showcases the power of AWS Amplify Gen 2’s infrastructure-as-code approach, making it easier than ever to build production-ready applications.</p><h3>Why AWS Amplify Gen 2?</h3><p>AWS Amplify Gen 2 represents a significant evolution in full-stack development. Unlike the previous generation, Gen 2 takes an infrastructure-as-code approach that provides:</p><ul><li><strong>Type-safe backend definitions</strong> — Define your backend resources using TypeScript</li><li><strong>Better local development</strong> — Improved sandbox environments for testing</li><li><strong>Simplified deployment</strong> — Streamlined CI/CD with automatic builds</li><li><strong>Enhanced developer experience</strong> — Better integration with modern frameworks like Next.js</li></ul><h3>Tech Stack Overview</h3><p>Here’s what powers our photo archive application:</p><ul><li><strong>Frontend</strong>: Next.js 14 with App Router and React 18</li><li><strong>Backend</strong>: AWS Amplify Gen 2 (Authentication, Storage, API)</li><li><strong>Styling</strong>: TailwindCSS for responsive design</li><li><strong>Cloud Services</strong>: AWS S3, Cognito, DynamoDB.</li></ul><h3>Setting Up the Development Environment</h3><h4>Prerequisites</h4><p>Before we start, make sure you have:</p><ul><li>Node.js 18+ installed</li><li>An AWS account</li><li>AWS CLI setup</li><li>Git for version control</li><li>Your favorite code editor</li></ul><h3>Project Initialization</h3><p>First, let’s clone the repository and install dependencies:</p><pre>git clone https://github.com/mahirberkano/photo-archive-app-amplify.git<br>cd photo-archive-app-amplify<br>npm install</pre><p>To run the development server:</p><pre>npm run dev</pre><p>Your app will be available at <a href="http://localhost:3000.">http://localhost:3000.</a></p><h3>AWS Amplify Gen 2 Backend Configuration</h3><h4>Amplify Resource Configuration</h4><p>The heart of our Amplify Gen 2 setup is the resource configuration. Here’s how we define our backend infrastructure:</p><pre>// backend.ts<br>import { defineBackend } from &#39;@aws-amplify/backend&#39;;<br>import { auth } from &#39;./auth/resource&#39;;<br>import { data } from &#39;./data/resource&#39;;<br>import { storage } from &#39;./storage/resource&#39;;<br>/**<br> * @see https://docs.amplify.aws/react/build-a-backend/ to add storage, functions, and more<br> */<br>const backend =defineBackend({<br>  auth,<br>  data,<br>  storage,<br>})<br><br>const { cfnUserPool } = backend.auth.resources.cfnResources<br>// an empty array denotes &quot;email&quot; and &quot;phone_number&quot; cannot be used as a username<br>cfnUserPool.usernameAttributes = []</pre><pre>// ./auth/resource.ts<br>import { defineAuth } from &#39;@aws-amplify/backend&#39;;<br><br>/**<br> * Define and configure your auth resource<br> * @see https://docs.amplify.aws/gen2/build-a-backend/auth<br> */<br>export const auth = defineAuth({<br>  loginWith: {<br>    email: true,<br>  },<br>    <br>  userAttributes: {<br>    preferredUsername: {<br>      mutable: true,<br>      required: true,<br>    }<br>  }<br>});</pre><pre>// ./data/resource<br>import { type ClientSchema, a, defineData } from &#39;@aws-amplify/backend&#39;;<br><br>=========================================================================*/<br>const schema = a.schema({<br>  Photo: a<br>    .model({<br>      fileName: a.string(),<br>      caption: a.string(),<br>      uploadedBy: a.string(),<br>      createdAt: a.datetime(),<br>    })<br>    .authorization((allow) =&gt; [allow.authenticated()]),<br><br>  Comment: a<br>    .model({<br>      id: a.id(),<br>      photoId: a.id(),<br>      text: a.string(),<br>      author: a.string(),<br>      createdAt: a.datetime(),<br>    })<br>    .authorization((allow) =&gt; [allow.authenticated()]),<br>});<br><br>export type Schema = ClientSchema&lt;typeof schema&gt;;<br><br>export const data = defineData({<br>  schema,<br>  authorizationModes: {<br>    defaultAuthorizationMode: &#39;userPool&#39;, // requires Cognito login<br>  },<br>});<br><br>/*======================================================================<br>Go to your frontend source code. From your client-side code, generate a<br>Data client to make CRUDL requests to your table. (THIS SNIPPET WILL ONLY<br>WORK IN THE FRONTEND CODE FILE.)<br><br>Using JavaScript or Next.js React Server Components, Middleware, Server <br>Actions or Pages Router? Review how to generate Data clients for those use<br>cases: https://docs.amplify.aws/gen2/build-a-backend/data/connect-to-API/<br>=========================================================================*/<br><br>/*<br>&quot;use client&quot;<br>import { generateClient } from &quot;aws-amplify/data&quot;;<br>import type { Schema } from &quot;@/amplify/data/resource&quot;;<br><br>const client = generateClient&lt;Schema&gt;() // use this Data client for CRUDL requests<br>*/<br><br>/*=======================================================================<br>Fetch records from the database and use them in your frontend component.<br>(THIS SNIPPET WILL ONLY WORK IN THE FRONTEND CODE FILE.)<br>=========================================================================*/<br><br></pre><pre>// ./storage/resource.ts<br>import { defineStorage } from &#39;@aws-amplify/backend&#39;;<br><br>export const storage = defineStorage({<br>  name: &#39;photoStorage&#39;,<br>  access: (allow) =&gt; ({<br>    &#39;public/*&#39;: [<br>      allow.authenticated.to([&#39;read&#39;, &#39;write&#39;]), // logged in users can upload + read<br>      allow.guest.to([&#39;read&#39;]),                  // guests can view<br>    ],<br>  }),<br>});</pre><h3>Setting Up the Sandbox Environment</h3><p>Amplify Gen 2 makes local development seamless with sandbox environments:</p><p><strong>Before using Amplify you must setup AWS CLI to your local environment!</strong></p><p>For more information about AWS CLI <a href="https://docs.aws.amazon.com/cli/">https://docs.aws.amazon.com/cli/</a></p><pre>npx ampx sandbox</pre><p>This command creates a temporary backend environment that mirrors your production setup. You’ll see the backend outputs generated in amplify_outputs.json, which contains all the configuration your frontend needs.</p><h3>Backend Structure</h3><p>Our backend is organized into logical modules:</p><pre>amplify/<br> ┣ auth/          # User authentication setup with Cognito<br> ┣ storage/       # S3 bucket configuration for photos<br> ┗ data/          # API and database schema in DynamoDB</pre><p>Each module is defined using TypeScript, providing type safety and better developer experience.</p><h3>Frontend Implementation with Next.js</h3><h4>Amplify Configuration</h4><p>In our Next.js app, we configure Amplify to connect with our backend:</p><pre>import { Amplify } from &#39;aws-amplify&#39;;<br>import outputs from &#39;../amplify_outputs.json&#39;;</pre><pre>Amplify.configure(outputs);</pre><p>This single line connects our frontend to all the backend services we’ve defined.</p><h3>Key Features Implementation</h3><p>Our photo archive app includes several key features:</p><p><strong>Photo Upload Component</strong> The upload functionality allows users to select and upload photos directly to S3 with automatic optimization and security.</p><p><strong>Gallery View</strong> Photos are displayed in a responsive grid layout, similar to Instagram’s interface, with lazy loading for optimal performance.</p><p><strong>User Authentication</strong> Built-in authentication flows handle user registration, login, and session management automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*-y8_TDpT2hwZrgmOpSkKbg.png" /><figcaption>User Authentication with AWS Cognito</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSfmzJvGhctC7ZoWKnz6TQ.png" /><figcaption>Profile</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeSPp5mJCg4agN383vqEhg.png" /><figcaption>Upload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVzXbx-ilXCikxfVw_nXnw.png" /><figcaption>Home Page Feed</figcaption></figure><h3>Deployment Process</h3><h4>Connecting to AWS Amplify Console</h4><p>The deployment process with Amplify Gen 2 is remarkably straightforward:</p><ol><li><strong>Push to GitHub</strong>: Commit your code to a GitHub repository</li><li><strong>Connect Repository</strong>: Link your GitHub repo in the Amplify Console</li><li><strong>Configure Build Settings</strong>: Amplify automatically detects your Next.js configuration</li><li><strong>Deploy</strong>: Every commit triggers an automatic deployment</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TGcQ5YMbaQ_r-MkNvAkcg.png" /></figure><h3>Build Configuration</h3><p>Amplify Gen 2 automatically handles the build process for Next.js applications. The platform recognizes your framework and applies the appropriate build settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWmPXxcaCkO6nM5unJSd1A.png" /><figcaption>This is where your deployments are shown with the console</figcaption></figure><h3>AWS Console Overview</h3><p>Once deployed, you can see all the AWS resources created by Amplify in your AWS Console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkS_T-JznGgRrvFAUJH1zA.png" /><figcaption>S3 created and shown in AWS Management Console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtfQE4TX6lUhFhhIvvIRNA.png" /><figcaption>Cognito user pool and users shown in AWS Management Console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUA7C3jZ931uII3HMMLPsw.png" /><figcaption>DynamoDB table created for comments and other IDs are shown in AWS Management Console</figcaption></figure><h3>Resource Management</h3><p>Amplify Gen 2 creates and manages various AWS services:</p><ul><li><strong>S3 Buckets</strong> for photo storage with automatic scaling</li><li><strong>Cognito User Pools</strong> for authentication</li><li><strong>DynamoDB </strong>for data storage such as comments.</li></ul><h3>Performance and Scalability</h3><p>Our photo archive app is built for scale:</p><ul><li><strong>Automatic Image Optimization</strong>: Photos are automatically optimized for web delivery</li><li><strong>CDN Distribution</strong>: CloudFront ensures fast global access</li><li><strong>Serverless Architecture</strong>: Pay only for what you use with automatic scaling</li><li><strong>Secure Access</strong>: Fine-grained permissions protect user data</li></ul><h3>Development Experience</h3><p>Working with Amplify Gen 2 and Next.js provides several developer benefits:</p><ul><li><strong>Type Safety</strong>: Full TypeScript support across frontend and backend</li><li><strong>Hot Reloading</strong>: Instant feedback during development</li><li><strong>Local Testing</strong>: Complete backend simulation in sandbox mode</li><li><strong>Automated Deployments</strong>: Git-based deployment workflow</li></ul><h3>Lessons Learned</h3><p>Building this photo archive app taught me several valuable lessons:</p><ol><li><strong>Infrastructure as Code</strong>: Defining backend resources in TypeScript dramatically improves maintainability</li><li><strong>Local Development</strong>: Sandbox environments make testing backend changes much faster</li><li><strong>Deployment Simplicity</strong>: Amplify’s CI/CD pipeline eliminates deployment complexity</li><li><strong>Scalability by Default</strong>: The serverless architecture scales automatically with user demand</li></ol><h3>Next Steps and Enhancements</h3><p>Potential improvements for the photo archive app include:</p><ul><li><strong>Social Features</strong>: Adding likes, comments, and sharing capabilities</li><li><strong>Advanced Search</strong>: Implementing photo search using AWS Rekognition</li><li><strong>Mobile App</strong>: Creating React Native version using the same backend</li><li><strong>Real-time Updates</strong>: Adding live photo feed updates</li><li><strong>Image Processing</strong>: Automatic tagging and organization features</li></ul><h3>Conclusion</h3><p>AWS Amplify Gen 2 with Next.js provides an incredibly powerful foundation for building modern web applications. The combination of type-safe backend definitions, seamless local development, and automatic scaling makes it an excellent choice for projects of any size.</p><p>The photo archive app demonstrates how quickly you can build and deploy a production-ready application with sophisticated features like user authentication, file storage, and cloud deployment.</p><p>Whether you’re a solo developer or part of a larger team, this tech stack offers the flexibility and power needed to bring your ideas to life quickly and efficiently.</p><h3>Resources</h3><ul><li><strong>Live Demo</strong>: <a href="https://main.d2y1dpbyx183v6.amplifyapp.com/">Photo Archive App</a></li><li><strong>GitHub Repository</strong>: <a href="https://github.com/mahirberkano/photo-archive-app-amplify">mahirberkano/photo-archive-app-amplify</a></li><li><strong>AWS Amplify Gen 2 Documentation</strong>: <a href="https://docs.amplify.aws/">AWS Amplify Docs</a></li><li><strong>Next.js Documentation</strong>: <a href="https://nextjs.org/docs">Next.js Docs</a></li><li><strong>AWS CLI: </strong><a href="https://docs.aws.amazon.com/cli/">https://docs.aws.amazon.com/cli/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90890c4c0668" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clerion/building-a-photo-archive-app-with-next-js-and-aws-amplify-gen-2-90890c4c0668">Building a Photo Archive App with Next.js and AWS Amplify Gen 2</a> was originally published in <a href="https://medium.com/clerion">Clerion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Serverless Audio Transcription with AWS]]></title>
            <link>https://medium.com/clerion/automating-serverless-audio-transcription-with-aws-e83729d849af?source=rss----4c23810537fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/e83729d849af</guid>
            <dc:creator><![CDATA[Eniscan Aslan]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 12:36:45 GMT</pubDate>
            <atom:updated>2025-04-22T12:35:53.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*DjET8D5rQ2fYWnuMYST4TQ.png" /></figure><h3>Introduction</h3><p>In modern cloud applications, automating the transcription of audio files is a powerful way to extract text from voice recordings. This article walks through an AWS Lambda function that leverages Amazon Transcribe to process and convert audio files uploaded to an S3 bucket into text format. We will explore how this Lambda function works step by step and the AWS services that make it possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5RX80QbMOxuRULwZHVgyA.png" /></figure><h3>AWS Services Used</h3><p>This solution primarily relies on the following AWS services:</p><ul><li><strong>AWS Lambda</strong>: Executes the transcription workflow automatically when a new audio file is uploaded.</li><li><strong>Amazon S3</strong>: Serves as storage for both the input audio files and the output transcriptions.</li><li><strong>Amazon Transcribe</strong>: Converts speech in the audio files into text.</li><li><strong>Amazon API Gateway</strong>: Used to serve transcriptions as subtitles dynamically for videos.</li></ul><pre>import os<br>import json<br>import boto3<br>import time<br><br>transcribe = boto3.client(&#39;transcribe&#39;)<br>s3 = boto3.client(&#39;s3&#39;)<br><br>def lambda_handler(event, context):<br>    print(event)<br>    output_bucket = &#39;funble-output&#39;<br>    <br>    # Loop through the records in the event (there might be multiple records)<br>    for record in event[&#39;Records&#39;]:<br>        bucket_name = record[&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>        object_key = record[&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]<br>        print(f&quot;Processing file: {object_key} from bucket: {bucket_name}&quot;)<br><br>        try:<br>            # Determine the language based on the folder structure<br>            if &quot;vo-tr/&quot; in object_key:<br>                language_code = &#39;tr-TR&#39;<br>            elif &quot;vo-en/&quot; in object_key:<br>                language_code = &#39;en-US&#39;<br>            else:<br>                raise Exception(&quot;File is not uploaded in the correct folder or is in an unsupported format.&quot;)<br><br>            print(f&quot;Selected language code: {language_code}&quot;)<br>            <br>            transcription_name = os.path.splitext(os.path.basename(object_key))[0]<br>            timestamp = time.strftime(&quot;%Y%m%d%H%M%S&quot;)<br>            job_name = f&quot;{transcription_name}_{timestamp}&quot;<br>            job_uri = f&quot;s3://{bucket_name}/{object_key}&quot;<br>            print(f&quot;Starting transcription job: {job_name}&quot;)<br><br>            # Start the transcription job with Amazon Transcribe<br>            transcribe.start_transcription_job(<br>                TranscriptionJobName=job_name,<br>                Media={&#39;MediaFileUri&#39;: job_uri},<br>                MediaFormat=&#39;mp3&#39;,<br>                LanguageCode=language_code,<br>                OutputBucketName=output_bucket<br>            )<br>            <br>            # Poll for job completion<br>            while True:<br>                status = transcribe.get_transcription_job(TranscriptionJobName=job_name)<br>                if status[&#39;TranscriptionJob&#39;][&#39;TranscriptionJobStatus&#39;] in [&#39;COMPLETED&#39;, &#39;FAILED&#39;]:<br>                    break<br>            <br>            # Check if transcription was successful<br>            if status[&#39;TranscriptionJob&#39;][&#39;TranscriptionJobStatus&#39;] == &#39;COMPLETED&#39;:<br>                transcript_file_obj = s3.get_object(Bucket=output_bucket, Key=job_name + &#39;.json&#39;)<br>                transcript_file_content = transcript_file_obj[&quot;Body&quot;].read().decode(&#39;utf-8&#39;)<br>                data = json.loads(transcript_file_content)<br>                text = data[&#39;results&#39;][&#39;transcripts&#39;][0][&#39;transcript&#39;]<br>                print(f&quot;Transcription completed successfully.&quot;)<br>                <br>                # Save the transcript to S3<br>                dest_folder_path = os.path.dirname(object_key)<br>                dest_file_path = os.path.join(dest_folder_path, f&quot;{transcription_name}.json&quot;)<br>                s3.put_object(Bucket=output_bucket, Key=dest_file_path, Body=transcript_file_content)<br>                s3.delete_object(Bucket=output_bucket, Key=job_name + &#39;.json&#39;)<br>                <br>                return {<br>                    &#39;statusCode&#39;: 200,<br>                    &#39;body&#39;: json.dumps(text)<br>                }<br>            else:<br>                print(&quot;Transcription failed.&quot;)<br>                return {<br>                    &#39;statusCode&#39;: 200,<br>                    &#39;body&#39;: json.dumps(&quot;Transcription failed.&quot;)<br>                }<br>        except Exception as e:<br>            print(f&quot;Error occurred: {str(e)}&quot;)<br>            return {<br>                &#39;statusCode&#39;: 200,<br>                &#39;body&#39;: json.dumps(str(e))<br>            }</pre><h3>Step-by-Step Breakdown of the Lambda Function</h3><h3>1. Handling S3 Event Triggers</h3><p>The function is triggered when a new MP3 file is uploaded to a specific folder in an S3 bucket. The event data contains details about the uploaded file, including the bucket name and object key. The Lambda function extracts this information to determine the language of the file:</p><pre>for record in event[&#39;Records&#39;]:<br>    bucket_name = record[&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>    object_key = record[&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]</pre><p>Depending on whether the file is in vo-en/ (English) or vo-tr/ (Turkish), the function sets the appropriate language code:</p><pre>if &quot;vo-tr/&quot; in object_key:<br>    language_code = &#39;tr-TR&#39;<br>elif &quot;vo-en/&quot; in object_key:<br>    language_code = &#39;en-US&#39;<br>else:<br>    raise Exception(&quot;The mp3 file was not placed in either vo-en/ or vo-tr/&quot;)</pre><h3>2. Preparing the Transcription Job</h3><p>The function extracts the file name and creates a unique transcription job name:</p><pre>transcription_name = os.path.splitext(os.path.basename(object_key))[0]<br>timestamp = time.strftime(&quot;%Y%m%d%H%M%S&quot;)<br>job_name = f&quot;{transcription_name}_{timestamp}&quot;<br>job_uri = f&quot;s3://{bucket_name}/{object_key}&quot;</pre><p>It then starts an Amazon Transcribe job, specifying the media file location, format, and language:</p><pre>transcribe.start_transcription_job(<br>    TranscriptionJobName=job_name,<br>    Media={&#39;MediaFileUri&#39;: job_uri},<br>    MediaFormat=&#39;mp3&#39;,<br>    LanguageCode=language_code,<br>    OutputBucketName=output_bucket<br>)</pre><h3>3. Polling for Transcription Completion</h3><p>The function continuously checks whether the transcription job has completed:</p><pre>while True:<br>    status = transcribe.get_transcription_job(TranscriptionJobName=job_name)<br>    if status[&#39;TranscriptionJob&#39;][&#39;TranscriptionJobStatus&#39;] in [&#39;COMPLETED&#39;, &#39;FAILED&#39;]:<br>        break</pre><p>If the job fails, an error message is logged. If successful, the transcription result is retrieved from the output S3 bucket.</p><h3>4. Storing and Cleaning Up Transcription Files</h3><p>Once the transcription is complete, the function retrieves the JSON output and extracts the transcript text:</p><pre>transcript_file_obj = s3.get_object(Bucket=output_bucket, Key=job_name + &#39;.json&#39;)<br>transcript_file_content = transcript_file_obj[&quot;Body&quot;].read().decode(&#39;utf-8&#39;)<br>data = json.loads(transcript_file_content)<br>text = data[&#39;results&#39;][&#39;transcripts&#39;][0][&#39;transcript&#39;]</pre><p>The transcript is then saved back to the output bucket in a structured format:</p><pre>dest_folder_path = os.path.dirname(object_key)<br>dest_file_path = os.path.join(dest_folder_path, f&quot;{transcription_name}.json&quot;)<br>s3.put_object(Bucket=output_bucket, Key=dest_file_path, Body=transcript_file_content)</pre><p>To keep the storage clean, the temporary transcription file is deleted:</p><pre>s3.delete_object(Bucket=output_bucket, Key=job_name + &#39;.json&#39;)</pre><h3>5. Using API Gateway for Subtitle Integration</h3><p>The transcribed text can now be accessed via API Gateway, enabling dynamic subtitle overlays on videos. This approach allows video players to fetch subtitles in real time, improving accessibility and user experience.</p><h3>Conclusion</h3><p>This AWS Lambda-based solution automates the entire process of transcribing audio files using Amazon Transcribe. It ensures a structured workflow by leveraging S3 event triggers, processing files based on their language, and cleaning up unnecessary files. The output text can then be integrated into applications such as subtitle generation via API Gateway.</p><p>By using a fully serverless approach, this architecture enables scalable, cost-efficient, and automated transcription workflows without requiring manual intervention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e83729d849af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clerion/automating-serverless-audio-transcription-with-aws-e83729d849af">Automating Serverless Audio Transcription with AWS</a> was originally published in <a href="https://medium.com/clerion">Clerion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSH into a Docker Container on AWS Fargate]]></title>
            <link>https://medium.com/clerion/ssh-into-a-docker-container-on-aws-fargate-1cf723b87c9b?source=rss----4c23810537fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/1cf723b87c9b</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Ata Ince]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 14:43:03 GMT</pubDate>
            <atom:updated>2025-04-16T15:10:00.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*d6yFsxBrvRBXHOolYobTZg@2x.png" /></figure><p>Setting up an SSH-accessible Docker container can be useful for debugging, remote management, and infrastructure prototyping. In this post, we’ll walk through how to:</p><ul><li><strong>Build a Docker image with SSH and Python</strong></li><li><strong>Push it to Amazon ECR</strong></li><li><strong>Deploy it serverlessly on AWS Fargate</strong></li><li><strong>Connect to it via SSH</strong></li></ul><h3>🏢 Step 1: Build the Docker Image</h3><p>We start by creating a Dockerfile that installs Python and an SSH server on an Ubuntu base image:</p><pre>FROM ubuntu:22.04<br># Install Python and OpenSSH<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y python3 openssh-server &amp;&amp; \<br>    apt-get clean<br># Prepare SSH<br>RUN mkdir /var/run/sshd &amp;&amp; \<br>    sed -i &#39;s/#PermitRootLogin prohibit-password/PermitRootLogin without-password/&#39; /etc/ssh/sshd_config &amp;&amp; \<br>    mkdir -p /root/.ssh &amp;&amp; chmod 700 /root/.ssh<br># Set working directory<br>WORKDIR /app<br># Add content for web server<br>RUN echo &quot;Hello World&quot; &gt; index.html<br># Expose necessary ports<br>EXPOSE 80 22<br># Start SSH and HTTP servers<br>CMD echo &quot;$SSH_PUBLIC_KEY&quot; &gt; /root/.ssh/authorized_keys &amp;&amp; \<br>    chmod 600 /root/.ssh/authorized_keys &amp;&amp; \<br>    service ssh start &amp;&amp; \<br>    python3 -m http.server 80</pre><p>Build it locally:</p><pre>docker buildx build --platform linux/amd64 -t ubuntu-hello-ssh .</pre><h3>🍎 Note for Apple Silicon Users</h3><p>If you’re using a Mac with Apple Silicon (ARM-based architecture), and you want your container to run on AWS infrastructure (which typically uses <strong>x86_64/amd64</strong>), you must specify the platform during the build process:</p><pre>docker buildx build --platform linux/amd64 -t ubuntu-hello-ssh .</pre><p>However, be aware:</p><blockquote>⚠️ A Docker image built with — platform=linux/amd64 may not run <strong>locally</strong> on an Apple Silicon machine unless you’re using emulation. You’ll see errors like exec format error if you try to run the image directly.</blockquote><p>So, in most cases:</p><ul><li>✅ Build for amd64 if you’re planning to <strong>deploy to AWS</strong></li><li>✅ Build for arm64 if you’re testing <strong>locally</strong> on Apple Silicon</li></ul><p>You can even build <strong>multi-arch images</strong> using Docker Buildx and — platform=linux/amd64,linux/arm64 for maximum compatibility.</p><h3>📤 Step 2: Pushing the Docker Image to Amazon ECR</h3><p>Now that your Docker image is built and working locally, let’s upload it to <strong>Amazon Elastic Container Registry (ECR)</strong>. This will allow us to later deploy it on AWS Fargate.</p><h4>🛠 Create a Private Repository</h4><p>First, create a private repository in the AWS Console.<br>Go to <strong>Amazon ECR → Private Registry → Create repository</strong>, give it a name (e.g., ssh-demo-repo), keep the default settings, and hit <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rR5kaVPj5tUCIf-RyTWZ6A.png" /></figure><h4>🔐 Authenticate Docker with ECR</h4><p>Use the following command to authenticate your Docker client with ECR:</p><pre>aws ecr get-login-password --region eu-central-1 | docker login --username AWS --password-stdin &lt;your-account-id&gt;.dkr.ecr.eu-central-1.amazonaws.com</pre><blockquote><em>Replace </em><em>&lt;your-account-id&gt; with your actual AWS Account ID.</em></blockquote><h4>🏷️ Tag the Existing Image</h4><p>Since your Docker image is already built, you just need to tag it with your ECR repository URI:</p><pre>docker tag ubuntu-hello-ssh:latest &lt;your-account-id&gt;.dkr.ecr.eu-central-1.amazonaws.com/ssh-demo-repo:latest</pre><h4>🚀 Push the Image to ECR</h4><p>Push the image using:</p><pre>docker push &lt;your-account-id&gt;.dkr.ecr.eu-central-1.amazonaws.com/ssh-demo-repo:latest</pre><p>Once pushed, your image will appear in the ECR console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zod6JOuurH9O98p7arBpyg.png" /></figure><h3>🚀 Step 3: Create an ECS Cluster</h3><p>Create a new cluster in the <strong>Amazon ECS Console</strong>:</p><ul><li><strong>Name:</strong> ssh-demo-cluster</li><li><strong>Infrastructure:</strong> AWS Fargate (serverless)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P25xGnSrbGJB3SeerZ2CCg.png" /></figure><h3>📊 Step 4: Define the Task Definition</h3><p>In the ECS Console:</p><ul><li>Go to <strong>Task Definitions</strong></li><li>Click <strong>Create new task definition with JSON</strong></li></ul><pre>{<br>  &quot;family&quot;: &quot;ssh-demo-task&quot;,<br>  &quot;networkMode&quot;: &quot;awsvpc&quot;,<br>  &quot;requiresCompatibilities&quot;: [&quot;FARGATE&quot;],<br>  &quot;cpu&quot;: &quot;256&quot;,<br>  &quot;memory&quot;: &quot;512&quot;,<br>  &quot;containerDefinitions&quot;: [<br>    {<br>      &quot;name&quot;: &quot;ssh-demo-container&quot;,<br>      &quot;image&quot;: &quot;&lt;your-account-id&gt;.dkr.ecr.eu-central-1.amazonaws.com/ssh-demo-repo:latest&quot;,<br>      &quot;portMappings&quot;: [<br>        {<br>          &quot;containerPort&quot;: 80,<br>          &quot;protocol&quot;: &quot;tcp&quot;<br>        },<br>        {<br>          &quot;containerPort&quot;: 22,<br>          &quot;protocol&quot;: &quot;tcp&quot;<br>        }<br>      ],<br>      &quot;environment&quot;: [<br>        {<br>          &quot;name&quot;: &quot;SSH_PUBLIC_KEY&quot;,<br>          &quot;value&quot;: &quot;ssh-rsa AAAAB3...your-public-key-here... user@host&quot;<br>        }<br>      ],<br>      &quot;essential&quot;: true<br>    }<br>  ],<br>  &quot;executionRoleArn&quot;: &quot;arn:aws:iam::&lt;your-account-id&gt;:role/ecsTaskExecutionRole&quot;<br>}</pre><blockquote><em>Replace </em><strong><em>&lt;your-account-id&gt;</em></strong><em> and the </em><strong><em>SSH_PUBLIC_KEY</em></strong><em> value with your own.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ziAG6k5vmxdyH5FBjFcLg.png" /></figure><blockquote><em>🔐 For production environments, replace the environment block with secrets to inject sensitive variables securely via </em><a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html"><em>AWS Secrets Manager</em></a><em>.</em></blockquote><h3>🌐 Step 5: Create a Fargate Service</h3><p>Go to your ECS Cluster, click <strong>Services → Create</strong>, then:</p><ul><li><strong>Launch type:</strong> Fargate</li><li><strong>Task definition:</strong> ssh-demo-task</li><li><strong>Service name:</strong> ssh-demo-container</li><li><strong>Number of tasks:</strong> 1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zod6JOuurH9O98p7arBpyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfELifD8EJWmEZequII1Qw.png" /></figure><p>Configure networking:</p><ul><li><strong>Select a public subnet</strong></li><li><strong>Enable public IP assignment</strong></li><li><strong>Use a security group allowing ports 80 and 22 (SSH only from your IP)</strong></li></ul><h3>🛡️ Step 6: Connect via SSH</h3><p>Once the task is running:</p><ul><li>Go to <strong>Tasks → ENI → Public IP</strong></li><li>SSH into your container:</li></ul><pre>ssh -i ~/.ssh/id_rsa root@&lt;public-ip&gt; -p 22 -o StrictHostKeyChecking=no</pre><p>You should be inside your Fargate-hosted Ubuntu container!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*UeeUQmgBCau7PF0ewp1y0A.png" /></figure><h3>🔒 Bonus: Use AWS Secrets Manager for Key Injection</h3><p>Instead of passing your key as an environment variable, use a more secure method:</p><ul><li>Store it in <strong>AWS Secrets Manager</strong>:</li><li>Reference it in your Task Definition JSON:</li></ul><pre>&quot;secrets&quot;: [<br>  {<br>    &quot;name&quot;: &quot;SSH_PUBLIC_KEY&quot;,<br>    &quot;valueFrom&quot;: &quot;arn:aws:secretsmanager:eu-central-1:&lt;your-account-id&gt;:secret:ssh-public-key-xxxxxx&quot;<br>  }<br>]</pre><p>This keeps your secrets encrypted and never exposed in plaintext.</p><h3>🌟 Summary</h3><blockquote><strong><em>✅ Built a Docker image with SSH and Python</em></strong></blockquote><blockquote><strong><em>✅ Pushed it to Amazon ECR</em></strong></blockquote><blockquote><strong><em>✅ Deployed it using ECS Fargate</em></strong></blockquote><blockquote><strong><em>✅ Connected to it securely via SSH</em></strong></blockquote><blockquote><strong><em>✅ Explored secure ways to inject credentials</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cf723b87c9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clerion/ssh-into-a-docker-container-on-aws-fargate-1cf723b87c9b">SSH into a Docker Container on AWS Fargate</a> was originally published in <a href="https://medium.com/clerion">Clerion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>