<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Peyman Mihankhah on Medium]]></title>
        <description><![CDATA[Stories by Peyman Mihankhah on Medium]]></description>
        <link>https://medium.com/@mihankhahp?source=rss-13c6173df1fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*a_ysdVXcptsmfWuI</url>
            <title>Stories by Peyman Mihankhah on Medium</title>
            <link>https://medium.com/@mihankhahp?source=rss-13c6173df1fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:50:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mihankhahp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Shrink the objects, and the AWS S3 discount tier costs more than S3 Standard]]></title>
            <link>https://medium.com/@mihankhahp/shrink-the-objects-and-the-aws-s3-discount-tier-costs-more-than-s3-standard-1bc8500e5886?source=rss-13c6173df1fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bc8500e5886</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[solution-design]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3-glacier]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Peyman Mihankhah]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 18:01:01 GMT</pubDate>
            <atom:updated>2026-08-18T18:01:01.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nASHlP6qKqsB7TrEXRoA2w.png" /></figure><p>S3 Standard, Standard-IA, Glacier Instant Retrieval and Intelligent-Tiering all return data in milliseconds from three availability zones. Here is the math that actually separates them.</p><p>Choosing between S3 Standard and Glacier Deep Archive is not a decision. One is 23x cheaper and takes twelve hours to read. If your data is cold, you already know the answer.</p><p>The real decision sits among the four millisecond-retrieval classes: S3 Standard, Standard-IA, Glacier Instant Retrieval, and Intelligent-Tiering. All four are 99.999999999% durable across three or more availability zones and return an object in milliseconds. So many teams pick by headline price per GB, a number wrong often enough to invert the ranking entirely.</p><p>Three workload variables decide it.</p><h3>Variable 1: how much you read</h3><p>Set the monthly cost expressions equal and solve for <em>f</em>, the fraction of stored bytes read per month, from us-east-1 list prices [1]. With large objects, where request charges are noise:</p><pre>Standard-IA vs Standard:      0.0125 + 0.010f = 0.023   → f = 104%<br>Glacier IR  vs Standard:      0.0040 + 0.030f = 0.023   → f =  61%<br>Glacier IR  vs Standard-IA:   0.0040 + 0.030f<br>                            = 0.0125 + 0.010f           → f =  42.5%</pre><p>The result contradicts how most teams use these tiers. <strong>Standard-IA</strong> stays <strong>cheaper </strong>than Standard<strong> until you read the entire dataset every month.</strong> Its $0.01/GB retrieval fee is smaller than the $0.0105/GB it saves on storage, so the tier labelled “infrequent access” wins at almost any access level. Glacier IR takes over below <strong>42.5%.</strong> <strong>If reads were the only variable, nobody would ever use S3 Standard. They are not.</strong></p><h3>Variable 2: average object size, which inverts variable 1</h3><p>Standard-IA, One Zone-IA and Glacier Instant Retrieval all bill a <strong>minimum of 128 KB per object</strong> [2]. Store a 32 KB thumbnail, and you pay for 128 KB, a silent 4x multiplier on storage. Solving for the size where it cancels the discount:</p><pre>Standard-IA:  0.0125 × (128/S) = 0.023  → S ≈ 70 KB<br>Glacier IR:   0.0040 × (128/S) = 0.023  → S ≈ 22 KB</pre><p>Below roughly 70 KB average object size,<strong> Standard-IA costs more than S3 Standard even if you never read a byte.</strong> Glacier IR holds out until 22 KB.</p><p>A GET costs $0.0004 per 1,000 on Standard but $0.01 on<strong> Glacier Instant Retrieval, a 25x premium</strong> [1, 5]. At 64 KB objects reading 8% of bytes monthly, Glacier IR costs $0.0235/GB-month, of which $0.0131(56% ) is GET requests. It ties with plain Standard.</p><p><strong>Intelligent-Tiering</strong> has the mirror-image problem. Its $0.0025 per 1,000 objects monthly fee [1, 6] is charged per object, not per GB, so its cost per GB scales inversely with object size:</p><pre>Avg object size  Monitoring cost     As % of Standard&#39;s storage price<br>128 KB           $0.02048/GB-mo                       89%<br>256 KB           $0.01024/GB-mo                       45%<br>1 MB             $0.00256/GB-mo                       11%<br>10 MB            $0.00026/GB-mo                       1%</pre><p>The Infrequent Access tier saves $0.0105/GB against Standard, exactly what monitoring costs at <strong>250 KB average object size</strong>. Below that, the fee consumes the entire benefit of the tier it moved your data into.</p><blockquote>The practical rule: under about 128 KB, tier selection stops being the lever.</blockquote><h3>Variable 3: access skew, which only Intelligent-Tiering can see</h3><p>Here is the variable nobody documents. The three fixed tiers price on <strong><em>how many bytes</em></strong> you read. Intelligent-Tiering prices on <strong><em>how many distinct objects</em></strong> you touch: it drops an object to Infrequent Access after 30 consecutive days without a read and to Archive Instant Access after 90, <strong>but any single access pulls it straight back to full-price Frequent Access [3]. Objects under 128 KB never move at all</strong> [4].</p><p>Same 1 MB objects, same 2% of bytes read per month, three different distributions of those reads:</p><pre>Reads Access pattern       Int-Tiering   Standard-IA   Glacier IR  Standard<br>spread over 80% of obj     $0.02347      $0.01272      $0.00480    $0.02301<br>spread over 40% of obj     $0.01672      $0.01272      $0.00480    $0.02301<br>concentrated in 3% of obj  $0.00773      $0.01272      $0.00480    $0.02301</pre><p><strong>Intelligent-Tiering’s price swings 3x across rows where every other tier is flat. In the top row, it costs more than S3 Standard, and 85% more than Standard-IA.</strong></p><p>This<strong> inverts </strong>the standard advice. “<strong>Use Intelligent-Tiering when access patterns are unpredictable</strong>” is only right when unpredictable means <em>concentrated but you don’t know where</em>.</p><blockquote>When it means thin reads scattered across the whole bucket, a search index, or an antivirus scan touching every object monthly, Intelligent-Tiering is the worst of the four.</blockquote><h3>Worked scenario, and what happens when you guess wrong</h3><p>A 40 TB document store: 30 million objects averaging 1.4 MB, 8% of bytes read per month, 12% of bytes hot, 70% untouched for over 90 days.</p><pre>Tier                  $/GB-month   $/month   $/year   Saved vs. Standard, per year<br><strong>Glacier IR            $0.00699     $286       $3,433          $7,883</strong><br>Intelligent-Tiering   $0.00966     $396       $4,749          $6,567<br>Standard-IA           $0.01336     $547       $6,566          $4,750<br>S3 Standard           $0.02302     $943       $11,316           —</pre><p>Glacier IR wins by 38%, <strong>$7,883 a year</strong> on one bucket. But that ranking rests on an 8% estimate, and access estimates are usually wrong. Sweeping <em>f</em> from 2% to 200% and measuring each tier’s worst-case gap against whichever tier was optimal:</p><pre>Tier                           Max regret<br>Intelligent-Tiering               +115%<br>Standard-IA                       +168%<br><strong>Glacier Instant Retrieval         +233%</strong><br>S3 Standard                       +385%</pre><p><strong>The cheapest tier at expected value is the second-worst under uncertainty. Glacier IR’s $0.03/GB retrieval fee turns vicious at 100% monthly reads, costing $0.041/GB, nearly double S3 Standard.</strong></p><blockquote>Its 90-day minimum duration [2] means that when you discover the mistake, you pay to keep the data there anyway.</blockquote><p><strong>Intelligent-Tiering</strong> has the lowest max regret because it has no retrieval fee and no minimum duration. It is not a cost-optimization tier but <strong>an insurance policy with a priced premium</strong>: $0.00183/GB-month of monitoring at 1.4 MB objects, buying immunity from guessing wrong.</p><h3>The decision rule</h3><p>Measure your average object size first; it can disqualify options before access patterns matter at all.</p><h4>If your average object is under 128 KB</h4><p>No storage class will help you; <strong>change how you write the data instead</strong>. Combine many small objects into fewer large ones before they reach S3: roll per-event logs into hourly bundles, write Parquet instead of one JSON blob per record, tar up thumbnail sets. <strong>40 TB of 32 KB objects in Standard-IA bills at the 128 KB floor: $0.05/GB, $2,048/month, $24,576/year.</strong> Pack the same bytes into 1 MB objects, and the floor stops applying: $0.0125/GB, $512/month, <strong>$6,144/year</strong>, and <strong>32x fewer GET requests</strong>.</p><p>That is <strong>$18,432 saved annually</strong> from the write path alone, more than any tier switch on offer, which is why object size is the first fix and the storage class the second.</p><h4>Over 128 KB</h4><p>Ask whether you know your access pattern. If CloudWatch says reads are <strong>under 40% of bytes monthly, take Glacier Instant Retrieval </strong>and accept the 90-day lock-in. If you don’t know, or the pattern is volatile, pay Intelligent-Tiering’s premium instead, but only if objects average over 250 KB, or the monitoring fee cancels the point.</p><p>And if reads are spread thin across every object, use Standard-IA. Intelligent-Tiering will bill you Frequent Access rates for the privilege of monitoring data it never moves.</p><p><em>All prices are AWS us-east-1 list rates for the first 50 TB/month storage tier, retrieved 17 August 2026, and exclude data transfer out. AWS changes these regularly — re-run the arithmetic against [1] before committing to a design. All break-even points, per-GB totals and annual figures are derived by the author from those list prices; the method is shown above, and the model is reproducible from the stated inputs.</em></p><h3>References</h3><ol><li>Amazon Web Services. <em>Amazon S3 Pricing.</em> <a href="https://aws.amazon.com/s3/pricing/">https://aws.amazon.com/s3/pricing/</a> (accessed 17 August 2026) — storage, request and retrieval list rates for all storage classes.</li><li>Amazon Web Services. <em>Understanding and managing Amazon S3 storage classes.</em> AWS Documentation, Amazon S3 User Guide. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-class-intro.html">https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-class-intro.html</a> (accessed 17 August 2026) — 128 KB minimum billable object size, and 30/90/180-day minimum storage durations.</li><li>Amazon Web Services. <em>Understanding S3 Intelligent-Tiering.</em> AWS Documentation, Amazon S3 User Guide. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/intelligent-tiering-overview.html">https://docs.aws.amazon.com/AmazonS3/latest/userguide/intelligent-tiering-overview.html</a> (accessed 17 August 2026) — the automatic tier-transition model: 30 consecutive days without access moves an object to Infrequent Access, 90 days to Archive Instant Access, and any access returns it to Frequent Access.</li><li>Amazon Web Services. <em>Amazon S3 Intelligent-Tiering — Improved Cost Optimizations for Short-Lived and Small Objects.</em> AWS News Blog. <a href="https://aws.amazon.com/blogs/aws/amazon-s3-intelligent-tiering-further-automating-cost-savings-for-short-lived-and-small-objects">https://aws.amazon.com/blogs/aws/amazon-s3-intelligent-tiering-further-automating-cost-savings-for-short-lived-and-small-objects</a> (accessed 17 August 2026) — objects under 128 KB are not monitored, not auto-tiered, and incur no minimum duration charge.</li><li>CloudOptimo. <em>A Look Into AWS S3 Pricing Models.</em> <a href="https://www.cloudoptimo.com/blog/a-look-into-aws-s3-pricing-models/">https://www.cloudoptimo.com/blog/a-look-into-aws-s3-pricing-models/</a> (accessed 17 August 2026) — per-1,000 GET request rates and per-GB retrieval fees by storage class.</li><li>Spendark. <em>S3 Storage Class Pricing: When Each Tier Actually Saves.</em> <a href="https://spendark.com/blog/s3-storage-class-pricing/">https://spendark.com/blog/s3-storage-class-pricing/</a> (accessed 17 August 2026) — cross-check on the $0.0025 per 1,000 objects Intelligent-Tiering monitoring fee.</li><li>CloudZero. <em>Amazon S3 Pricing: The Complete 2026 Guide.</em> <a href="https://www.cloudzero.com/blog/s3-pricing/">https://www.cloudzero.com/blog/s3-pricing/</a> (accessed 17 August 2026) — cross-check on per-GB storage rates.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bc8500e5886" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 5 — Why I Put cdk synth in GitHub Actions Before I Added Deployment]]></title>
            <link>https://medium.com/@mihankhahp/part-5-why-i-put-cdk-synth-in-github-actions-before-i-added-deployment-f34d60100d3f?source=rss-13c6173df1fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f34d60100d3f</guid>
            <category><![CDATA[layer-2-solution]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <dc:creator><![CDATA[Peyman Mihankhah]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 14:43:36 GMT</pubDate>
            <atom:updated>2026-07-21T14:43:36.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrPZeT45aDgXRCSWSNtIJA.png" /></figure><p><em>Part 5 of 5 in the series: </em><strong><em>One Static Website, Three AWS CDK Layers</em></strong></p><p>In Part 1, I explained why I built this repo around one architecture and three CDK layers.</p><p>In Part 2, I used L2 as the practical baseline.</p><p>In Part 3, I dropped to L1 to expose the wiring.</p><p>In Part 4, I climbed to L3 to see what happens when a pattern starts making architectural decisions for me.</p><p>This final part is about what comes next.</p><p>Because once I have three different ways to express the same infrastructure, the question is no longer just:</p><blockquote><em>Which layer do I prefer?</em></blockquote><p>It becomes:</p><blockquote><em>How do I validate that the repo still does what I think it does?</em></blockquote><p>That is why I ended this project with a GitHub Actions workflow built around one very specific command:</p><pre>cdk synth</pre><p>Not deploy.<br>Not a full pipeline.<br>Just synthesize first.</p><p>That choice was deliberate.</p><p>AWS documents cdk synth as the command that synthesizes a CDK app into a cloud assembly, including CloudFormation templates for each stack. The CDK CLI also uses synthesis as the basis for most operations, because it needs fresh templates before comparing or deploying stacks.</p><p>So for me, synth is not a cosmetic step.</p><p>It is the first real proof that the repo still holds together.</p><h3>Why I wanted the series to end here</h3><p>If the first four parts were about <strong>authoring infrastructure</strong>, this last part is about <strong>trusting infrastructure code enough to keep evolving it</strong>.</p><p>That matters even more in this repo because I am not maintaining one stack.</p><p>I am maintaining:</p><ul><li>an L1 version,</li><li>an L2 version,</li><li>an L3 version,</li><li>plus a single entry point that chooses between them.</li></ul><p>That is a lot of moving parts for a small project.</p><p>And once I reached that point, I did not want the repo to depend on “it worked on my laptop” as the only validation strategy.</p><p>So I added a workflow.</p><p>Not because the repo was large.</p><p>Because it was already opinionated enough to deserve automated feedback.</p><h3>The workflow is intentionally small</h3><p>The workflow lives <a href="https://github.com/Mihankhahp/AWS-CDK-L1-L2-L3-static-site/tree/main/.github/workflows">here</a> :</p><p>.github/workflows/infrastructure-synth.yml</p><p>And it is intentionally simple:</p><pre>name: Infrastructure Synth<br>on:<br>  push:<br>    paths:<br>      - &#39;infrastructure/**&#39;<br>      - &#39;.github/workflows/infrastructure-synth.yml&#39;<br>jobs:<br>  synth:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: actions/setup-node@v4<br>        with:<br>          node-version: &#39;20&#39;<br>          cache: &#39;npm&#39;<br>          cache-dependency-path: infrastructure/package-lock.json<br>      - name: Install (infrastructure)<br>        working-directory: infrastructure<br>        run: npm ci<br>      - name: CDK Synth<br>        working-directory: infrastructure<br>        run: npx -y aws-cdk@latest synth</pre><p>That is not an accident.</p><p>I did not want the first workflow in this repo to be “deploy to AWS and hope the guardrails show up later.”</p><p>I wanted the first workflow to answer a narrower question:</p><blockquote><em>Can the CDK app still boot, resolve its context, and generate valid templates from source?</em></blockquote><p>That is what cdk synth gives me.</p><h3>Why I started with synth instead of deploy</h3><p>There are a few reasons I think synth is the right first automation step for a repo like this.</p><h3>1. It validates the infrastructure definition without requiring deployment</h3><p>The CDK docs are very clear that synthesis produces the cloud assembly and the stack templates before deployment happens. That means I can validate the structure of the app and the generated CloudFormation without turning CI into a release system on day one.</p><h3>2. It keeps the feedback loop cheap</h3><p>When I change stack code, I want the earliest signal possible that I broke something. Synth is much cheaper than discovering the same issue at deployment time.</p><h3>3. It fits the purpose of this repo</h3><p>This project is a comparison repo. Its value is in how the infrastructure is modelled. So validating the generated templates is not secondary work here. It is core to the design.</p><p>That is why ending the series with workflow validation feels right to me.</p><p>It closes the loop.</p><h3>What cdk synth is really doing for me</h3><p>One of the reasons I like synthesis so much is that it makes the invisible visible.</p><p>CDK source code is not the thing AWS deploys.</p><p>CloudFormation templates are.</p><p>And synth is the step where that transformation becomes concrete.</p><p>AWS describes the output as a <strong>cloud assembly</strong>, which includes the CloudFormation template for each stack and any referenced asset metadata.</p><p>That is especially important in this repo because the abstraction level changes what the source code hides.</p><p>In Part 2, L2 hid a lot of low-level policy and origin wiring.<br> In Part 4, L3 hid even more by packaging defaults into a pattern.</p><p>Synthesis is the place where I can stop arguing from source code and inspect what the repo is actually producing.</p><p>That is not just helpful.<br>It is the only fair way to compare the layers.</p><h3>In this repo, synth is where the abstractions become comparable</h3><p>This is probably the most important connection between Part 4 and Part 5.</p><p>When I look only at source files, the L3 version looks dramatically smaller than the L2 and L1 versions.</p><p>But once I synthesize the stacks, I can see what that compactness is buying me:</p><ul><li>extra resources,</li><li>logging infrastructure,</li><li>security-header behavior,</li><li>lifecycle helpers,</li><li>and the rest of the pattern’s defaults.</li></ul><p>AWS documents the CloudFrontToS3 pattern as including secure defaults such as CloudFront access logging, S3 access logging, Origin Access Control, and automatic HTTP security headers.</p><p>That is exactly why synthesis matters.</p><p>Without synthesis, a pattern can look deceptively lightweight.</p><p>With synthesis, I can inspect the real infrastructure footprint.</p><p>So, for this repo, cdk synth is not just a CI check.</p><p>It is part of the teaching model.</p><h3>The workflow also reflects a real repo detail</h3><p>One thing I ran into while working on this repo is version drift between the local CDK CLI and the library version in infrastructure/package.json.</p><p>In the repo today:</p><ul><li>aws-cdk is pinned as a dev dependency at 2.1105.0</li><li>while aws-cdk-lib is newer at ^2.237.1</li></ul><p>That is why the workflow uses this:</p><pre>run: npx -y aws-cdk@latest synth</pre><p>I wanted the CI job to avoid unnecessary CLI/library friction and focus on the actual state of the app.</p><p>That choice may look small, but it is the kind of thing that makes a workflow feel dependable instead of fragile.</p><p>In other words, the workflow is not only validating the infrastructure.</p><p>It is also smoothing out one class of avoidable tooling mismatch.</p><h3>Why does the workflow only target the infrastructure path</h3><p>I also kept the trigger scoped:</p><pre>on:<br>  push:<br>    paths:<br>      - &#39;infrastructure/**&#39;<br>      - &#39;.github/workflows/infrastructure-synth.yml&#39;</pre><p>That reflects how I think about this repo.</p><p>The infrastructure workflow should run when:</p><ul><li>the infrastructure changes,</li><li>or the workflow itself changes.</li></ul><p>Not every repository event deserves a full infrastructure validation run.</p><p>This is a small choice, but it keeps the signal relevant.</p><p>And because the workflow is small, I want the trigger to be small too.</p><h3>The Node setup is part of the predictability story</h3><p>The workflow uses actions/setup-node Node 20 and npm caching:</p><pre>- uses: actions/setup-node@v4<br>  with:<br>    node-version: &#39;20&#39;<br>    cache: &#39;npm&#39;<br>    cache-dependency-path: infrastructure/package-lock.json</pre><p>GitHub recommends setup-node as the standard way to configure Node.js in Actions jobs, and its docs show npm dependency caching through the same action.</p><p>That matters here for a simple reason:</p><p>I want CI to be boring.</p><p>Not creative.<br>Not surprising.<br>Not “works differently on every runner.”</p><p>The more deterministic the environment is, the more useful the synth result becomes.</p><h3>What this workflow catches well</h3><p>For this repo, Synth is good at catching the exact kinds of problems I care about early.</p><h3>It catches broken app wiring</h3><p>If I break the app entry point or context resolution, Synth fails before anything reaches AWS.</p><h3>It catches invalid stack definitions</h3><p>If one of the stacks stops producing a valid template, the synth fails immediately.</p><h3>It catches abstraction-layer regressions</h3><p>Because this repo is explicitly about the L1/L2/L3 comparison, I want early feedback whenever a change breaks the assumptions inside one of those layers.</p><h3>It catches generated-template surprises</h3><p>This is especially useful for L3, where a short source file can still produce a larger-than-expected template.</p><p>That is what makes synthesis such a natural fit here.</p><p>It validates both the app and the architecture story.</p><h3>What this workflow does not catch yet</h3><p>Just as important: I do not want to oversell what the workflow is doing.</p><p>It does <strong>not</strong> prove everything.</p><p>It does not tell me:</p><ul><li>whether the deployed site renders correctly,</li><li>whether a custom domain is configured the way I want,</li><li>whether a browser receives the responses I expect,</li><li>or whether my infrastructure behaviour matches every runtime assumption.</li></ul><p>And in this repo specifically, it also does not replace proper tests.</p><p>The current test/infrastructure.test.js file is still just the default scaffold placeholder. So at the moment, the real automated confidence in the repo comes much more from synthesis than from assertions.</p><p>That is useful, but incomplete.</p><p>AWS recommends synthesizing templates before deployment and comparing them when validating migrated or generated infrastructure, which is exactly the mindset I wanted here.</p><p>The next level would be adding template assertions and making the test suite say something meaningful.</p><h3>The most honest thing about this workflow: it validates the default path first</h3><p>There is also a detail here that I think is worth being explicit about.</p><p>The current workflow runs:</p><pre>npx -y aws-cdk@latest synth</pre><p>with no extra context.</p><p>And in this repo, the default layer in bin/infrastructure.js is:</p><pre>const layerRaw =<br>  app.node.tryGetContext(&#39;layer&#39;) ?? process.env.CDK_LAYER ?? &#39;l3&#39;;</pre><p>So the workflow is currently validating the <strong>default path first</strong>, which is the L3 implementation.</p><p>I actually think that is a reasonable starting point.</p><p>It validates the repo’s default user experience.</p><p>But it also reveals the next obvious improvement:<br>Run synth across multiple layer values, not just the default one.</p><p>That is the kind of refinement I like making after the basic feedback loop is already stable.</p><h3>If I extend this workflow, I know exactly where I’d go next</h3><p>Because this is the last article in the series, I want to be honest about what I see as the next step rather than pretending the current workflow is finished.</p><p>If I keep evolving this repo, I would most likely extend the workflow in three directions.</p><h3>1. Synthesize all three layers</h3><p>Right now, the workflow validates the default L3 path.<br> The natural next step is a small matrix or repeated synth runs for:</p><ul><li>l1</li><li>l2</li><li>l3</li></ul><p>That would make the repo’s core comparison promise testable in CI.</p><h3>2. Add assertion-based tests</h3><p>Not just “does synth run,” but “does the generated template contain the properties I expect?”</p><h3>3. Consider pull_request in addition to push</h3><p>The current workflow is already useful, but a pull-request signal would make the feedback even earlier.</p><p>I did not need all of that to make the repo valuable.</p><p>But I do think those are the right directions once the synth-first foundation is in place.</p><h3>Why I still think synth was the right place to stop</h3><p>It would have been easy to turn this final part into a full CI/CD article.</p><p>But that would have drifted away from what the repo is really doing.</p><p>This project is fundamentally about how one architecture changes across CDK layers.</p><p>So the most appropriate final step is not “ship everything automatically.”</p><p>It is:</p><blockquote><em>make the generated infrastructure visible, repeatable, and checkable.</em></blockquote><p>That is what synth does.</p><p>It creates a feedback loop that is close enough to the source code to help me iterate, but close enough to the generated templates to keep me honest.</p><p>And for this repo, that is the right ending.</p><h3>What I want the reader to take away from the whole series</h3><p>If someone reads all five parts in order, the journey I wanted them to have is this:</p><ul><li>In <strong>Part 1</strong>, they understand what the repo is trying to teach.</li><li>In <strong>Part 2</strong>, they see the practical L2 baseline.</li><li>In <strong>Part 3</strong>, they understand what the higher-level abstractions were hiding.</li><li>In <strong>Part 4</strong>, they see what a pattern gives them in exchange for more opinionated defaults.</li><li>In <strong>Part 5</strong>, they understand why validation belongs in the story from the beginning.</li></ul><p>That is the full arc I wanted when I built the repo.</p><p>Not just:<br>“Here are three ways to write AWS CDK.”</p><p>But:</p><blockquote><em>“here is how abstraction changes both the code you write and the way you need to validate it.”</em></blockquote><p>That, more than anything else, is what this repo taught me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f34d60100d3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4 : Letting the Pattern Decide: Rebuilding the Same Static Website with AWS CDK L3]]></title>
            <link>https://medium.com/@mihankhahp/part-4-letting-the-pattern-decide-rebuilding-the-same-static-website-with-aws-cdk-l3-1dc80dd45a06?source=rss-13c6173df1fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dc80dd45a06</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Peyman Mihankhah]]></dc:creator>
            <pubDate>Thu, 14 May 2026 21:31:04 GMT</pubDate>
            <atom:updated>2026-05-14T21:31:44.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrPZeT45aDgXRCSWSNtIJA.png" /></figure><p><em>Part 4 of 5 in the series: </em><strong><em>One Static Website, Three AWS CDK Layers</em></strong></p><p>In Part 2, I used L2 as the practical baseline.</p><p>In Part 3, I dropped down to L1 so I could see every moving part that the higher-level constructs were hiding.</p><p>Now I want to go in the opposite direction.</p><p>I want to climb up to <strong>L3</strong> and ask a different question:</p><blockquote><em>What happens when I stop composing the architecture myself and let a pattern do more of the design work for me?</em></blockquote><p>That is what this part of the repo is about.</p><p>AWS describes L3 constructs as <strong>patterns</strong>: higher-level constructs that combine multiple resources into a working architecture with opinionated defaults. They sit above L2, trade some flexibility for speed, and are built to solve a recognizable use case rather than expose one AWS resource at a time.</p><p>That is exactly what I wanted to test in this repo.</p><p>Not whether L3 writes less code.</p><p>That part is obvious.</p><p>What I wanted to understand was whether the reduction in code was worth the increase in abstraction.</p><h3>The file this article is about</h3><p>This part of the series lives here:</p><p><a href="https://github.com/Mihankhahp/aws-cdk-static-website/blob/main/infrastructure/lib/static-website-stack-L3.js">infrastructure/lib/static-website-stack-L3.js</a></p><p>And the line that defines the whole experience is this one:</p><pre>import { CloudFrontToS3 } from &#39;@aws-solutions-constructs/aws-cloudfront-s3&#39;;</pre><p>That import changes the shape of the stack immediately.</p><p>In Part 2, I was still composing the architecture by hand with L2 building blocks:</p><ul><li>an S3 bucket,</li><li>an origin,</li><li>a CloudFront distribution,</li><li>and the behaviour around them.</li></ul><p>In Part 4, I stop assembling those pieces one by one and start from a pattern that already assumes they belong together.</p><p>That is the key shift.</p><h3>Why I wanted an L3 version in this repo</h3><p>I did not add the L3 stack just to show a shorter alternative.</p><p>I added it because I wanted the repo to answer the full abstraction question.</p><p>If Part 3 asked:<br> <strong>“What does this architecture look like when I own every detail?”</strong></p><p>Then Part 4 asks:<br> <strong>“What does it look like when I accept a reusable architectural opinion?”</strong></p><p>That is what an L3 pattern really is.</p><p>AWS Prescriptive Guidance describes L3 constructs as patterns that provision and connect multiple resources to solve a specific problem, often by composing underlying L2 constructs and carrying their own defaults and interactions.</p><p>That makes L3 fundamentally different from both L1 and L2.</p><p>It is not just “nicer syntax.”</p><p>It is a packaged answer to a design problem.</p><h3>In this repo, the pattern is CloudFrontToS3</h3><p>Here is the core of the L3 stack:</p><pre>const pattern = new CloudFrontToS3(this, `StaticSite-${stage}-${version}`, {<br>      // S3 bucket settings (pattern already defaults to secure settings;<br>      // we override removal behavior here)<br>      bucketProps: {<br>        removalPolicy,<br>        autoDeleteObjects: removalPolicy === RemovalPolicy.DESTROY,<br>        // IMPORTANT: don’t hardcode bucketName unless you truly need it (global + replacement risk).<br>      },<br><br>      // CloudFront Distribution overrides<br>      cloudFrontDistributionProps: {<br>        defaultRootObject: &#39;index.html&#39;,<br>        comment: `static-site ${stage} ${version}`,<br>        defaultBehavior: {<br>          viewerProtocolPolicy:<br>            cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,<br>          compress: true,<br>          allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,<br>          cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,<br>        },<br><br>        // SPA routing (optional). Remove if not needed.<br>        errorResponses: [<br>          {<br>            httpStatus: 403,<br>            responseHttpStatus: 200,<br>            responsePagePath: &#39;/index.html&#39;,<br>          },<br>          {<br>            httpStatus: 404,<br>            responseHttpStatus: 200,<br>            responsePagePath: &#39;/index.html&#39;,<br>          },<br>        ],<br>      },<br>    });</pre><p>This is the part of the repo where the contrast becomes sharpest.</p><p>In L2, I still had to declare the bucket, create the origin, and build the distribution.</p><p>In L3, I mostly describe the behaviour I want to override:</p><ul><li>lifecycle behaviour for the bucket,</li><li>default root object,</li><li>HTTPS redirect,</li><li>compression,</li><li>allowed methods,</li><li>cache policy,</li><li>and SPA fallback behaviour.</li></ul><p>Everything else starts coming from the pattern itself.</p><p>That is the promise of L3.</p><h3>What the pattern gives me before I ask for anything</h3><p>The CloudFrontToS3 pattern is documented by AWS Solutions Constructs as an out-of-the-box pairing of CloudFront and S3 with a set of secure defaults. The official defaults include CloudFront access logging, automatic HTTP security headers, and an origin path of /Origin Access Control for the S3 origin, S3 access logging, versioning, blocked public access, and retained buckets by default.</p><p>That matters because it means the L3 version is not merely saving me lines of code.</p><p>It is bringing an architectural opinion with it.</p><p>And that opinion is much broader than the code in my file might suggest.</p><p>When I look at static-website-stack-L3.jsthe stack looks compact.<br> When I look at what it synthesizes, I see the real size of the pattern.</p><p>That is the central lesson of this part.</p><h3>Fewer lines of code do not mean fewer resources</h3><p>This is the most important thing the L3 version taught me.</p><p>When I synthesize this stack in the repo, the generated template includes more than just:</p><ul><li>one S3 bucket,</li><li>one OAC,</li><li>and one CloudFront distribution.</li></ul><p>It also includes:</p><ul><li>additional S3 buckets for logging,</li><li>bucket policies for those buckets,</li><li>a CloudFront Function for security headers,</li><li>And, when I choose to destroy behaviour, the usual cleanup resources are needed to empty buckets before deletion.</li></ul><p>So the source file gets shorter.</p><p>But the infrastructure does not get smaller.</p><p>That is exactly what I wanted this repo to make visible.</p><p>L3 reduces <strong>authoring effort</strong>.<br> It does not necessarily reduce <strong>infrastructure footprint</strong>.</p><p>In fact, in this case, it intentionally adds more infrastructure because the pattern is trying to deliver a safer baseline.</p><h3>The hidden win: security headers and logging show up automatically</h3><p>This is where L3 starts to feel less like a convenience wrapper and more like a strong architectural default.</p><p>The AWS Solutions Constructs documentation explicitly says the pattern enables:</p><ul><li>CloudFront access logging,</li><li>S3 access logging,</li><li>Origin Access Control,</li><li>and automatic injection of best-practice HTTP security headers.</li></ul><p>That matches what I see when I inspect the synthesized stack:</p><ul><li>logging buckets exist,</li><li>OAC exists,</li><li>and a CloudFront Function is attached to inject security headers on responses.</li></ul><p>This is a very good example of the L3 trade-off.</p><p>If I had written the stack by hand, I would have had to decide whether to add each of those things.<br> With the pattern, those choices are largely made for me.</p><p>That is powerful.</p><p>It is also exactly why I do not think L3 should be the first thing a reader sees in this repo.</p><p>Without the context from Parts 2 and 3, it is too easy to mistake this for “magic.”</p><p>It is not magic.<br>It is a packaged infrastructure judgment.</p><h3>What I still control in the L3 stack</h3><p>Even though the pattern is opinionated, it is not sealed off.</p><p>That was one reason I wanted this specific version in the repo: it still gives me useful override points.</p><p>In my stack, I override:</p><ul><li>bucketProps</li><li>cloudFrontDistributionProps</li></ul><p>That lets me keep the same story I established earlier in the series:</p><ul><li>index.html as the default root object,</li><li>HTTPS redirect,</li><li>optimized caching,</li><li>GET/HEAD/OPTIONS only,</li><li>and SPA fallbacks for 403 and 404.</li></ul><p>So the L3 version is not “hands off.”</p><p>It is more accurate to say this:</p><blockquote><em>I stop designing from zero and start customizing a predesigned shape.</em></blockquote><p>That is a very different experience from both L1 and L2.</p><h3>Lifecycle behaviour gets more interesting at L3</h3><p>One of the most revealing details in this repo is the way lifecycle behaviour works in the L3 stack.</p><p>The pattern documentation says the S3 bucket is retained by default when the stack is deleted.</p><p>In my implementation, I explicitly override that for the primary site bucket:</p><pre>const removalPolicy = retainPreviousVersion<br>  ? RemovalPolicy.RETAIN<br>  : RemovalPolicy.DESTROY;</pre><p>And then:</p><pre>bucketProps: {<br>  removalPolicy,<br>  autoDeleteObjects: removalPolicy === RemovalPolicy.DESTROY,<br>},</pre><p>That sounds straightforward, but the synthesized result is more nuanced.</p><p>The primary site bucket can be switched into destroy mode, but some of the pattern’s supporting resources still retain their own opinions. In practice, that means the synthesized template can still keep logging-related buckets on retain even when the site bucket is configured for destroy.</p><p>That is a subtle but important L3 lesson.</p><p>A pattern is not just one resource with one policy.<br> It is a small architecture, and its internal defaults may not all move in lockstep with your one override.</p><p>That is another reason I believe every L3-heavy project needs regular cdk synth as part of the workflow.</p><p>We will come back to that in Part 5.</p><h3>L3 changes what I need to know</h3><p>One of the biggest differences between Part 3 and Part 4 is the kind of knowledge I need.</p><p>In L1, I needed to know:</p><ul><li>exact resource schemas,</li><li>property names,</li><li>policy shapes,</li><li>and how to wire IDs, ARNs, and resource attributes manually.</li></ul><p>In L3, I need a different kind of understanding:</p><ul><li>what the pattern includes by default,</li><li>what it exposes publicly,</li><li>which override points are safe,</li><li>and how to verify what got generated.</li></ul><p>That is a different skill set.</p><p>And I think that is why people sometimes misjudge L3.</p><p>L3 is not “easier” in every sense.</p><p>It is easier to <strong>start</strong>.<br> But it requires more trust in the abstraction, and more discipline in reviewing what the pattern actually produced.</p><h3>The exposed resources are still important</h3><p>Another detail I like in this repo is that I do not treat the pattern as a black box.</p><p>The stack still exposes useful outputs from the pattern:</p><pre>new CfnOutput(this, &#39;BucketName&#39;, {<br>  value: pattern.s3BucketInterface.bucketName,<br>});<br><br>new CfnOutput(this, &#39;CloudFrontDomain&#39;, {<br>  value: pattern.cloudFrontWebDistribution.domainName,<br>});<br><br>new CfnOutput(this, &#39;CloudFrontDistributionId&#39;, {<br>  value: pattern.cloudFrontWebDistribution.distributionId,<br>});</pre><p>That lines up with the pattern documentation, which says it CloudFrontToS3 exposes the created distribution, the S3 bucket interface, and the Origin Access Control as accessible properties.</p><p>I like this because it keeps the stack usable even though it is more abstract.</p><p>The pattern builds the architecture, but I can still interact with the important outputs instead of pretending the internal resources do not exist.</p><p>That makes the abstraction more practical.</p><h3>What L3 does better than L2 in this repo</h3><p>After building all three versions, I think L3 wins in a few clear ways.</p><h3>1. It gets me to a secure baseline faster</h3><p>The pattern comes with logging, OAC, and security-header behaviour already built into the design.</p><h3>2. It reduces repetitive infrastructure composition</h3><p>I do not have to rebuild the common CloudFront-plus-S3 relationship from scratch.</p><h3>3. It nudges the stack toward consistency</h3><p>If I wanted a team to provision this pattern repeatedly, I would trust the L3 version to keep more of the baseline decisions consistent.</p><p>Those are real advantages.</p><p>They are not just stylistic preferences.</p><h3>What L3 gives up</h3><p>At the same time, I would not call the L3 version the “best” version of this repo without qualification.</p><p>It gives up a few things, too.</p><h3>1. The architecture is less visible in the source file</h3><p>That is fine once I understand the pattern, but not ideal when I am still learning.</p><h3>2. The defaults are broader than they first appear</h3><p>That can be good, but it can also surprise people who equate fewer lines with fewer resources.</p><h3>3. Customization starts from the pattern’s worldview</h3><p>That is different from L2, where I am composing the architecture more directly.</p><p>For me, that is the real trade-off:</p><ul><li>L2 feels like I am designing with good tools.</li><li>L3 feels like I am editing a strong template.</li></ul><p>Both are useful.<br> They are just useful in different ways.</p><h3>Why Part 4 had to come after Parts 2 and 3</h3><p>This article only works because the earlier parts came first.</p><p>Part 2 gave the series a practical center of gravity.<br>Part 3 showed the cost of owning every detail.<br>Part 4 can now ask the opposite question without losing the reader.</p><p>If I had started the series with L3, the repo would look deceptively simple.</p><p>But now the contrast is doing useful work.</p><p>I can see exactly what changed:</p><ul><li>fewer handwritten resources,</li><li>more inherited defaults,</li><li>more generated infrastructure,</li><li>and a stronger architectural opinion.</li></ul><p>That is the connective tissue I wanted across the whole series.</p><h3>Takeaway</h3><p>The takeaway from this part is not just “L3 is faster.”</p><p>It is this:</p><blockquote><strong><em>L3 gives me speed by packaging architecture decisions, not by removing architecture.</em></strong></blockquote><p>That distinction matters.</p><p>In this repo, the pattern buys me a strong starting point:</p><ul><li>private S3,</li><li>CloudFront in front,</li><li>OAC,</li><li>logging,</li><li>security headers,</li><li>and sane delivery behaviour.</li></ul><p>But it also asks me to accept more defaults, more generated resources, and a little less transparency in the source file.</p><p>That is why I see L3 as the fastest route to a mature baseline <strong>when the pattern matches what I want</strong>.</p><h3>Next</h3><p>In Part 5, I will close the series by showing why cdk synth GitHub Actions matter so much here. Because once patterns start doing more work for me, validation stops being optional and becomes part of the design process itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dc80dd45a06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3 : Stripping Away the Convenience: Rebuilding the Same Static Website with AWS CDK L1…]]></title>
            <link>https://medium.com/@mihankhahp/part-3-stripping-away-the-convenience-rebuilding-the-same-static-website-with-aws-cdk-l1-2486b0e20e92?source=rss-13c6173df1fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2486b0e20e92</guid>
            <dc:creator><![CDATA[Peyman Mihankhah]]></dc:creator>
            <pubDate>Mon, 04 May 2026 16:01:02 GMT</pubDate>
            <atom:updated>2026-05-14T21:31:29.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrPZeT45aDgXRCSWSNtIJA.png" /></figure><h3>Part 3 : Stripping Away the Convenience: Rebuilding the Same Static Website with AWS CDK L1 Constructs</h3><p><em>Part 3 of 5 in the series: </em><strong><em>One Static Website, Three AWS CDK Layers</em></strong></p><p>In Part 2, I used the L2 stack as the practical baseline.</p><p>That was intentional.</p><p>I wanted to start with the version I would most likely use in a real project: readable, expressive, and still close enough to the architecture that nothing important disappears.</p><p>Now I want to go the other direction.</p><p>I want to remove that convenience layer and look at the same architecture through <strong>L1 constructs</strong>.</p><p>This is where the repo stops feeling like “CDK as a nice developer experience” and starts feeling like “CloudFormation with code.”</p><p>AWS describes L1 constructs as the lowest-level CDK resources, generated directly from the CloudFormation specification and typically prefixed with Cfn. They map very closely to the underlying AWS resource model.</p><p>That is exactly what this part of the repo is for.</p><p>I did not build the L1 version because I thought it would be the most elegant implementation.</p><p>I built it because I wanted to see, in code, what the L2 version was saving me from.</p><h3>The file this article is about</h3><p>If Part 2 lived in the practical middle, Part 3 lives here:</p><p><a href="https://github.com/Mihankhahp/aws-cdk-static-website/blob/main/infrastructure/lib/static-website-stack-L1.js">infrastructure/lib/static-website-stack-L1.js</a></p><p>This file is the lowest-level implementation in the repo, but it is still organized in a way I find useful.</p><p>Instead of putting the whole stack in one monolithic constructor, I split it into three focused pieces:</p><ul><li>WebsiteBucket</li><li>CloudFrontOac</li><li>WebsiteDistribution</li></ul><p>They all live in the same file, but each one owns a distinct concern.</p><p>That mattered to me because once you drop down to L1, the code gets noisy fast. Separating the concerns was my way of keeping the stack readable even when the abstraction level got much lower.</p><h3>The architecture is the same. The experience is not.</h3><p>The important thing to remember is that I am still building the same architecture from Parts 1 and 2:</p><ul><li>private S3</li><li>CloudFront in front</li><li>OAC for origin access</li><li>HTTPS redirect</li><li>SPA fallback to index.html</li></ul><p>None of that changes.</p><p>What changes is the amount of infrastructure intent the code can express for me automatically.</p><p>With L2, I could say:</p><pre>const origin =<br>  origins.S3BucketOrigin.withOriginAccessControl(websiteBucket);</pre><p>That one line carried a lot of meaning.</p><p>With L1, I have to build the pieces myself.</p><p>That is the whole story of this article.</p><h3>L1 starts with raw resources</h3><p>Here is the bucket creation in the L1 version:</p><pre>this.bucket = new s3.CfnBucket(this, &#39;Bucket&#39;, {<br>  bucketName, publicAccessBlockConfiguration: {<br>    blockPublicAcls: true,<br>    blockPublicPolicy: true,<br>    ignorePublicAcls: true,<br>    restrictPublicBuckets: true,<br>  },<br>  bucketEncryption: {<br>    serverSideEncryptionConfiguration: [<br>      {<br>        serverSideEncryptionByDefault: {<br>          sseAlgorithm: &#39;AES256&#39;,<br>        },<br>      },<br>    ],<br>  },<br>  versioningConfiguration: { status: &#39;Enabled&#39; },<br>});</pre><p>That code is doing the same job as the L2 bucket from Part 2.</p><p>But the difference is obvious immediately.</p><p>In L2, I wrote:</p><ul><li>blockPublicAccess</li><li>encryption</li><li>enforceSSL</li><li>versioned</li></ul><p>In L1, I am no longer speaking in the vocabulary of a higher-level S3 construct. I am speaking in the vocabulary of the CloudFormation resource schema itself. That is what AWS means when it says L1 constructs closely mirror CloudFormation resources.</p><p>That is not inherently bad.<br>But it changes the kind of work I am doing.</p><h3>In L1, even the “friendly defaults” become my responsibility</h3><p>One of the clearest examples is TLS enforcement.</p><p>In Part 2, I got this behaviour with:</p><pre>enforceSSL: true,</pre><p>That is clean. It tells the story in one property.</p><p>In L1, there is no equivalent convenience flag. So I implemented the policy myself:</p><pre>this._policyStatements = [<br>  {<br>    Sid: &#39;EnforceTLS&#39;,<br>    Effect: &#39;Deny&#39;,<br>    Principal: &#39;*&#39;,<br>    Action: &#39;s3:*&#39;,<br>    Resource: [<br>      `arn:aws:s3:::${bucketName}`,<br>      `arn:aws:s3:::${bucketName}/*`,<br>    ],<br>    Condition: {<br>      Bool: { &#39;aws:SecureTransport&#39;: &#39;false&#39; },<br>    },<br>  },<br>];</pre><p>And then attached it with a CfnBucketPolicy.</p><p>This is one of the best examples of what L1 feels like in practice.</p><p>Nothing is hidden.<br>But nothing is normalized for me either.</p><p>I have to know not just that I want TLS enforced, but also how that should be represented as an S3 bucket policy.</p><p>That is the trade-off.</p><h3>OAC becomes a separate construct, and I have to think about it explicitly</h3><p>In the L2 stack, OAC felt almost like part of the origin definition.</p><p>In L1, it becomes its own resource:</p><pre>const oac = new cloudfront.CfnOriginAccessControl(this, &#39;Oac&#39;, {<br>  originAccessControlConfig: {<br>    name: props.name,<br>    originAccessControlOriginType: &#39;s3&#39;,<br>    signingBehavior: &#39;always&#39;,<br>    signingProtocol: &#39;sigv4&#39;,<br>    description: &#39;OAC for private S3 origin&#39;,<br>  },<br>});</pre><p>I actually like this for learning.</p><p>It makes OAC impossible to ignore.</p><p>CloudFront recommends Origin Access Control for S3 origins, and its documentation treats OAC as the modern, recommended approach for private S3 access behind CloudFront.</p><p>In L2, I benefited from that best practice through a more ergonomic interface.</p><p>In L1, I had to instantiate it directly and wire it into the distribution myself.</p><p>That is more work, but it also makes the underlying architecture easier to see.</p><h3>The CloudFront distribution is where L1 really shows its personality</h3><p>The distribution definition is the part of the L1 stack that best captures the feel of this layer:</p><pre>const distribution = new cloudfront.CfnDistribution(this, &#39;Distribution&#39;, {<br>  distributionConfig: {<br>    enabled: true,<br>    comment: `static-site ${props.stage} ${props.version}`,<br>    defaultRootObject: &#39;index.html&#39;,<br>    httpVersion: &#39;http2&#39;,<br>    priceClass: &#39;PriceClass_100&#39;,<br>    origins: [<br>      {<br>        id: originId,<br>        domainName: props.bucket.bucketRegionalDomainName,<br>        originAccessControlId: props.oacId,<br>        originPath: props.originPath,<br>        s3OriginConfig: {},<br>      },<br>    ],<br>    defaultCacheBehavior: {<br>      targetOriginId: originId,<br>      viewerProtocolPolicy:<br>        cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,<br>      allowedMethods: [&#39;GET&#39;, &#39;HEAD&#39;, &#39;OPTIONS&#39;],<br>      cachedMethods: [&#39;GET&#39;, &#39;HEAD&#39;, &#39;OPTIONS&#39;],<br>      compress: true,<br>      forwardedValues: {<br>        queryString: false,<br>        cookies: { forward: &#39;none&#39; },<br>      },<br>    },<br>    customErrorResponses: [<br>      {<br>        errorCode: 403,<br>        responseCode: 200,<br>        responsePagePath: &#39;/index.html&#39;,<br>      },<br>      {<br>        errorCode: 404,<br>        responseCode: 200,<br>        responsePagePath: &#39;/index.html&#39;,<br>      },<br>    ],<br>    viewerCertificate: {<br>      cloudFrontDefaultCertificate: true,<br>    },<br>  },<br>});</pre><p>AWS’s CfnDistribution is the raw CloudFormation-backed distribution construct. You work directly with the distribution config shape instead of the more intention-revealing L2 interface.</p><p>This one block tells you almost everything about L1:</p><ul><li>It is explicit,</li><li>It is powerful,</li><li>And it is much less forgiving.</li></ul><p>Even the cache behaviour feels lower-level. In Part 2, I used cachePolicy: CACHING_OPTIMIZED. Here I have to think in terms of forwardedValues, cached methods and the shape of the CloudFront resource model itself.</p><p>That is not just more verbose.<br>It is a different mental model.</p><h3>The subtle thing L1 forces me to learn</h3><p>One of the most valuable things about building the L1 version was this:</p><p><strong>It forced me to stop assuming that resource properties look the same across abstraction levels.</strong></p><p>That sounds obvious, but it only really sinks in when you write the code.</p><p>In L2, the bucket and origin relationship feels natural because the constructs are designed to work together.</p><p>In L1, I have to be much more aware of:</p><ul><li>what property actually exists,</li><li>whether it is a ref or an attr,</li><li>whether I am dealing with a resource name, a physical ID, or an ARN,</li><li>and whether a value is ready to use in another resource definition.</li></ul><p>This is where L1 teaches the most.</p><p>It is also where mistakes get easier to make.</p><p>That is why I see L1 less as the version I would start from and more as the version that sharpened my understanding of what the higher-level layers were doing for me.</p><h3>The line that best explains why L1 matters</h3><p>If I had to choose one moment in the file that captures the whole point of L1, it would be this method:</p><pre>  allowCloudFrontRead(distributionId) {<br>    const account = Stack.of(this).account;<br><br>    this._policyStatements.push({<br>      Sid: &#39;AllowCloudFrontReadViaOAC&#39;,<br>      Effect: &#39;Allow&#39;,<br>      Principal: { Service: &#39;cloudfront.amazonaws.com&#39; },<br>      Action: &#39;s3:GetObject&#39;,<br>      Resource: [`arn:aws:s3:::${this.bucket.bucketName}/*`],<br>      Condition: {<br>        StringEquals: {<br>          &#39;AWS:SourceArn&#39;: `arn:aws:cloudfront::${account}:distribution/${distributionId}`,<br>        },<br>      },<br>    });<br><br>    // Re-assign policyDocument so CDK notices the change<br>    this.bucketPolicy.policyDocument = {<br>      Version: &#39;2012-10-17&#39;,<br>      Statement: this._policyStatements,<br>    };<br>  }<br>}</pre><p>This is the point in the stack where I am no longer just declaring resources.</p><p>I am manually coordinating them.</p><p>I create the distribution.<br>I get its ID.<br>Then I patch the bucket policy so only that distribution can read from the bucket through the CloudFront service principal.</p><p>That policy shape follows CloudFront’s documented OAC approach: allow the cloudfront.amazonaws.com service principal and scope access to a specific distribution ARN.</p><p>This is exactly the kind of wiring L2 hid from me in Part 2.</p><p>And this is exactly why I wanted this L1 version in the repo.</p><p>Because until you’ve done this manually once, it is easy to underestimate how much value the higher-level constructs are adding.</p><h3>L1 made the stack more educational, not more comfortable</h3><p>I do not think the L1 version is the nicest one in this repo.</p><p>I do think it is the most educational.</p><p>It taught me a few things very quickly:</p><h3>1. Higher-level constructs are not just shorter</h3><p>They encode decisions, relationships, and safe integration points.</p><h3>2. CloudFront + S3 is not a one-resource story</h3><p>There is always policy wiring, origin configuration, and service-to-service trust involved.</p><h3>3. The abstraction boundary matters</h3><p>At L1, I am constantly dealing with the exact shape of AWS resources. At L2, I am dealing with a model of intent.</p><p>That is a meaningful difference.</p><h3>What I kept from L2, and what I had to rebuild</h3><p>One thing I wanted to preserve in the L1 stack was parity of architecture.</p><p>So I kept the same core behaviours:</p><ul><li>private bucket</li><li>HTTPS redirect</li><li>SPA routing</li><li>OAC-backed access</li></ul><p>But I had to rebuild the implementation details by hand:</p><ul><li>public access block configuration</li><li>encryption block</li><li>TLS deny policy</li><li>OAC resource creation</li><li>distribution config</li><li>bucket policy update for CloudFront access</li></ul><p>That is the right way to think about this version.</p><blockquote>L1 did not change what I wanted.<br>It changed how much of the journey I had to own myself.</blockquote><h3>When I would actually choose L1</h3><p>After building this repo, my answer is pretty simple:</p><p>I would choose L1 when I need one of these things:</p><ul><li>direct access to a new AWS feature before the L2 construct catches up,</li><li>precise control over a CloudFormation resource shape,</li><li>or a deeper debugging path when the higher-level abstraction is hiding too much.</li></ul><p>AWS explicitly describes L1 constructs as useful when you need complete control over resource properties or when you are already comfortable thinking in CloudFormation terms.</p><p>That matches my experience here.</p><p>I would not choose L1 just because it feels “more advanced.”</p><p>In this repo, L1 was valuable because it made the underlying mechanics visible, not because it made the implementation better by default.</p><h3>Why Part 3 had to come after Part 2</h3><p>This article only works because Part 2 came first.</p><p>If I had started the series with L1, the reader would have met the most demanding version of the code before seeing the cleaner, more practical baseline.</p><p>That would have made the repo feel heavier than it really is.</p><p>By putting L2 first, I gave the architecture a readable center of gravity.</p><p>Now L1 has a purpose:<br><strong>It explains what was underneath that convenience.</strong></p><p>That is the connection I wanted across the series.</p><p>Part 1 introduced the repo.<br>Part 2 established the practical baseline.<br>Part 3 reveals the machinery.</p><h3>Takeaways from Part 3</h3><p>The takeaway from this part is not “L1 is better.”</p><p>It is this:</p><blockquote><strong><em>L1 shows me the cost of owning every detail yourself.</em></strong></blockquote><p>That cost buys visibility and control.</p><p>But it also buys more manual wiring, more CloudFormation-shaped code, and more opportunities to trip over resource-level details that the higher abstractions smooth out.</p><p>For this repo, L1 made me a better reader of the L2 version.</p><p>And that was the whole point.</p><p>In Part 4, I’ll go in the opposite direction and climb up from the practical baseline into the more opinionated end of the spectrum: <strong>L3 constructs</strong>.</p><p>That is where the question stops being “what do I have to wire myself?” and becomes “what am I willing to let a pattern decide for me?”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2486b0e20e92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2 : Why Start with L2: The Practical Baseline]]></title>
            <link>https://medium.com/@mihankhahp/part-2-why-start-with-l2-the-practical-baseline-caef2d4305b3?source=rss-13c6173df1fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/caef2d4305b3</guid>
            <dc:creator><![CDATA[Peyman Mihankhah]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 16:01:05 GMT</pubDate>
            <atom:updated>2026-05-14T21:32:07.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrPZeT45aDgXRCSWSNtIJA.png" /></figure><p>Part 2 of 5 in the series: <strong>One Static Website, Three AWS CDK Layers</strong></p><p>In Part 1, I explained why I built this repo the way I did.</p><p>To make one thing visible in code: <strong>how the same AWS architecture feels at different CDK abstraction layers.</strong></p><p>Now it’s time to start with the version I consider the practical baseline in this repo:</p><p><strong>The L2 implementation.</strong></p><blockquote><em>If </em><strong><em>L1 is the “show me every wire” </em></strong><em>version, and </em><strong><em>L3 is the “give me a pattern with opinions”</em></strong><em> version, </em><strong><em>L2 is the middle ground </em></strong><em>I’d reach for first in a real project.</em></blockquote><p>AWS positions L2 constructs as higher-level, intent-driven abstractions over raw CloudFormation resources, and that is exactly why this version is the best place to begin.</p><p>This article is a guided tour of that stack.</p><p>I’ll show:</p><ul><li>Why I consider L2 the sweet spot here,</li><li>What the stack actually creates,</li><li>Which choices are deliberate,</li><li>And what this implementation still leaves in my hands.</li></ul><h3>The file I want you to read first</h3><p>If you cloned the repo and asked me where to start, I’d point you here:</p><p><a href="https://github.com/Mihankhahp/aws-cdk-static-website/blob/main/infrastructure/lib/static-website-stack-L2.js">infrastructure/lib/static-website-stack-L2.js</a></p><p>That file is where the architecture becomes both <strong>clear</strong> and <strong>usable</strong>.</p><p>It’s still explicit enough that you can see the moving parts. But it’s no longer forcing you to wire up raw CloudFormation properties for everything manually.</p><p>That balance is why I chose it as the first implementation to unpack in this series.</p><h3>Why L2 is the right starting point</h3><p>I built three versions of the same architecture, but I did not build them because I think all three are equally pleasant to work in.</p><p>They are not.</p><p><strong>L2 is where I get the best trade-off:</strong></p><ul><li><strong>enough abstraction to remove repetitive infrastructure plumbing,</strong></li><li><strong>enough clarity to keep the architecture visible,</strong></li><li><strong>and enough control to make real design choices without fighting the framework.</strong></li></ul><p>That is the real value of this stack.</p><p>I’m not using L2 because it is “simpler” in a vague sense.<br>I’m using it because it lets the <strong>code express intent cleanly</strong>:</p><ul><li>private bucket,</li><li>CloudFront in front,</li><li>OAC for access,</li><li>HTTPS-only viewer behaviour,</li><li>SPA fallback behaviour.</li></ul><p>That is exactly the level of signal I want in infrastructure code.</p><h3>I treat stage and version as metadata, not bucket identity</h3><p>One of the design decisions I made early was this:</p><p><strong>I did not want the version to define the bucket itself.</strong></p><p>That is why the stack leans on tags and optional naming instead of baking versioning into physical resource identity.</p><p>Here is the relevant section:</p><pre>Tags.of(this).add(&#39;Stage&#39;, stage);<br>Tags.of(this).add(&#39;Version&#39;, version);<br>Tags.of(this).add(&#39;Account&#39;, account);<br>Tags.of(this).add(&#39;Region&#39;, region);<br><br>const bucketName = bucketBaseName<br>  ? safeBucketName(`${bucketBaseName}-${stage}-${account}-${region}`)<br>  : undefined;</pre><p>That choice was deliberate.</p><p>S3 bucket names are global, and replacing buckets casually is usually the wrong kind of excitement. So in this stack, version is something I want attached to the deployment context, not something I want forcing physical bucket replacement.</p><p>If I ever want immutable application versions, I would rather do that with object prefixes or a content deployment strategy than by turning the bucket name into a release artifact.</p><h3>The bucket is private on purpose</h3><p>The S3 bucket configuration is where the L2 stack starts paying off immediately:</p><pre>const websiteBucket = new s3.Bucket(this, `WebsiteBucket-${stage}`, {<br>  bucketName,<br>  blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,<br>  encryption: s3.BucketEncryption.S3_MANAGED,<br>  enforceSSL: true,<br>  versioned: true,<br>  removalPolicy,<br>  autoDeleteObjects: removalPolicy === RemovalPolicy.DESTROY,<br>});</pre><p>This is one of those places where L2 feels right.</p><p>The intent is obvious:</p><ul><li>block public access,</li><li>enable server-side encryption,</li><li>enforce SSL,</li><li>keep versioning on,</li><li>decide whether the bucket should be retained or destroyed.</li></ul><p>And those are exactly the options the CDK Bucket construct is built to express. The CDK S3 Bucket construct documents of these properties directly, including blockPublicAccess, encryption, enforceSSL, versioned, removalPolicy, and autoDeleteObjects.</p><p>This is the first big reason I like the L2 version:<br> I can read the bucket definition and understand the security posture in a few seconds.</p><h3>retainPreviousVersion changes more than one thing</h3><p>This repo exposes a flag called retainPreviousVersion, but the effect is really about the <strong>resource lifecycle</strong>.</p><p>In the L2 stack, that flag controls this:</p><pre>const removalPolicy = retainPreviousVersion<br>  ? RemovalPolicy.RETAIN<br>  : RemovalPolicy.DESTROY;</pre><p>That one line has a second-order effect here:</p><pre>autoDeleteObjects: removalPolicy === RemovalPolicy.DESTROY,</pre><p>So when I choose destroy behaviour, I’m not just saying “delete the stack.”</p><p>I’m also telling CDK to make bucket deletion possible by emptying the bucket.</p><p>And that has a very visible consequence in the synthesized template.</p><p>When I synthesize this stack in destroy mode, the template does not contain only:</p><ul><li>an S3 bucket,</li><li>a bucket policy,</li><li>an Origin Access Control,</li><li>and a CloudFront distribution,</li></ul><p>but also:</p><ul><li>a custom resource,</li><li>an IAM role,</li><li>and a Lambda function used to clean out the bucket before deletion.</li></ul><p>When I synthesize it in retain mode, those extra cleanup resources disappear.</p><p>I like this because it makes lifecycle behaviour explicit. The stack is small, but it is not pretending that deletion is free.</p><h3>The one line that makes the architecture click</h3><p>If Part 1 explained the architecture conceptually, this is the line that turns it into real infrastructure:</p><pre>const origin =<br>  origins.S3BucketOrigin.withOriginAccessControl(websiteBucket);</pre><p>This is the exact kind of abstraction I wanted from L2.</p><p>It says what I mean:</p><ul><li>Use this S3 bucket as the origin,</li><li>and configure it with Origin Access Control.</li></ul><p>The CDK origin helper documents withOriginAccessControl() Specifically for creating an S3 origin with OAC configured, and the CloudFront docs recommend OAC over the legacy OAI model for S3 origins.</p><p>That matters because the architecture I wanted was never “public bucket plus CDN.”<br> It was always a <strong>private bucket plus CloudFront-controlled access</strong>.</p><p>And L2 gives me a very clean line of code for that.</p><h3>What CDK is quietly doing for me here</h3><p>This is where the L2 implementation becomes especially satisfying.</p><p>Because the source code stays clean, but the synthesized infrastructure still ends up doing the right things.</p><p>When I synthesize the stack, I get:</p><ul><li>an AWS::CloudFront::OriginAccessControl,</li><li>a CloudFront distribution that points to the bucket’s regional domain name,</li><li>and a bucket policy that allows cloudfront.amazonaws.com to read objects only when the request comes from the specific CloudFront distribution.</li></ul><p>That policy shape aligns with CloudFront’s documented OAC setup: grant the CloudFront service principal access through a bucket policy and scope it with the distribution ARN.</p><p>That is exactly the kind of hidden plumbing I want L2 to absorb for me.</p><p>I still understand the architecture.<br> I just do not have to hand-author every low-level permission edge myself.</p><h3>The distribution is small, but it says a lot</h3><p>Here is the CloudFront distribution definition:</p><pre>const distribution = new cloudfront.Distribution(<br>  this,<br>  `Distribution-${stage}-${version}`,<br>  {<br>    defaultBehavior: {<br>      origin,<br>      viewerProtocolPolicy:<br>        cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,<br>      compress: true,<br>      allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,<br>      cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,<br>    },<br>    defaultRootObject: &#39;index.html&#39;,<br>    errorResponses: [<br>      {<br>        httpStatus: 403,<br>        responseHttpStatus: 200,<br>        responsePagePath: &#39;/index.html&#39;,<br>      },<br>      {<br>        httpStatus: 404,<br>        responseHttpStatus: 200,<br>        responsePagePath: &#39;/index.html&#39;,<br>      },<br>    ],<br>  },<br>);</pre><p>I like this block because it captures almost the entire delivery story in one place.</p><p>The CloudFront CDK library models distributions around origins and behaviours, with a default behaviour routing requests to the primary origin and controlling things like HTTPS redirects and supported HTTP methods.</p><p>In this stack, I’m using that model to say:</p><ul><li>send traffic to the S3 origin,</li><li>redirect viewers to HTTPS,</li><li>compress responses,</li><li>keep the allowed methods tight,</li><li>Use the default optimized cache policy,</li><li>serve index.html by default,</li><li>and make SPA routes work by mapping 403 and 404 back to /index.html.</li></ul><p>That is a lot of useful behaviour for a relatively small definition.</p><h3>Why the SPA fallback lives at CloudFront</h3><p>The fallback behaviour is one of the easiest details to miss:</p><pre>errorResponses: [<br>  {<br>    httpStatus: 403,<br>    responseHttpStatus: 200,<br>    responsePagePath: &#39;/index.html&#39;,<br>  },<br>  {<br>    httpStatus: 404,<br>    responseHttpStatus: 200,<br>    responsePagePath: &#39;/index.html&#39;,<br>  },<br>],</pre><p>I included that because many frontend apps use client-side routing. If a user visits /dashboard directly, I don’t want CloudFront treating that as a missing file and stopping there.</p><p>I want the app shell to load and let the frontend router take over.</p><p>That one choice pushes this repo from “static file hosting example” closer to “real frontend hosting baseline.”</p><p>It also makes the L2 version feel honest: this is not a toy stack pretending production apps only ever request /index.html.</p><h3>What this stack intentionally does not do</h3><p>I also want to be clear about what the L2 stack is not trying to do.</p><p>It does <strong>not</strong>:</p><ul><li>create a custom domain,</li><li>provision an ACM certificate,</li><li>create Route 53 records,</li><li>upload site assets,</li><li>or implement a full deployment pipeline.</li></ul><p>That is intentional.</p><p>This stack is focused on the <strong>hosting infrastructure baseline</strong>:</p><ul><li>private storage,</li><li>controlled origin access,</li><li>CloudFront delivery,</li><li>and sane defaults.</li></ul><p>Keeping that scope narrow is part of why the comparison across L1, L2, and L3 stays useful. If I had mixed in domains, certificates, DNS, uploads, and CI/CD all at once, the abstraction-layer comparison would get noisier.</p><p>I wanted this repo to teach one thing at a time.</p><h3>L2 is not “magic,” and that’s why I like it</h3><p>One reason I trust the L2 implementation more than the L3 pattern as a teaching baseline is that I can still mentally map almost every line to a concrete AWS concern.</p><p>I can look at the bucket block and say:<br> “That’s storage posture.”</p><p>I can look at the origin line and say:<br> “That’s CloudFront-to-S3 access.”</p><p>I can look at the distribution block and say:<br> “That’s delivery behaviour.”</p><p>That is exactly where I want an infrastructure abstraction to land.</p><p>L2 removes friction.<br>It does not erase the architecture.</p><p>And for me, that is the sweet spot.</p><h3>How I’d run this stack from the repo today</h3><p>Because this article is grounded in the actual repo, I want to mention one practical detail.</p><p>The package.json pins are older aws-cdk CLI than the currentaws-cdk-lib, so a plain local npx cdk synth can hit a schema mismatch. In practice, the most reliable command here is the same approach I used in CI:</p><pre>cdk synth -c stage=dev -c version=0.0.1 -c layer=l2</pre><p>And for deployment:</p><pre>cdk deploy -c stage=dev -c version=0.0.1 -c layer=l2</pre><p>If I want retained resources instead of destroying behaviour:</p><pre>cdk deploy -c stage=dev -c version=0.0.1 -c layer=l2 -c retainPreviousVersion=true</pre><p>That small adjustment keeps the article aligned with the repo as it actually behaves today.</p><h3>Takeaway</h3><p>If<strong> Part 1 </strong>was about understanding the<strong> repo</strong>,<strong> Part 2</strong> is about understanding the<strong> version </strong>I would most readily build on.</p><p>The takeaway is simple:</p><blockquote><strong><em>L2 is where this architecture becomes both readable and reusable.</em></strong></blockquote><p>It gives me a private S3 bucket, CloudFront delivery, OAC-based access, SPA routing, and controlled lifecycle behaviour without making me hand-wire every CloudFormation detail.</p><p>That is why I built this version first in spirit, even if not first in the file list.</p><h3>Next</h3><p>In Part 3, I’ll go the other direction and strip away the convenience layer.<br> We’ll rebuild the same architecture with <strong>L1 constructs</strong> and look at what the L2 version was saving me from.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caef2d4305b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1 — Understand AWS CDK Layers, Not Just Deploy a Static Website]]></title>
            <link>https://medium.com/@mihankhahp/part-1-understand-aws-cdk-layers-not-just-deploy-a-static-website-24cd866fb7b7?source=rss-13c6173df1fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/24cd866fb7b7</guid>
            <category><![CDATA[aws-cloudformation]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-oac]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <dc:creator><![CDATA[Peyman Mihankhah]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 16:01:04 GMT</pubDate>
            <atom:updated>2026-05-15T13:53:12.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrPZeT45aDgXRCSWSNtIJA.png" /></figure><h3>Part 1 : Understand AWS CDK Layers, Not Just Deploy a Static Website</h3><p>Part 1 of 5 in the series: <strong>One Static Website, Three AWS CDK Layers</strong></p><p>Most AWS CDK examples teach you one thing: how to deploy a stack.</p><p>That’s useful, but it leaves out the part that actually matters once you start building real infrastructure:</p><p><strong>How does the same architecture change depending on the abstraction level you choose?</strong></p><p>That is exactly why I built this repo.</p><p><a href="https://github.com/Mihankhahp/AWS-CDK-L1-L2-L3-static-site">[GITHUB LINK]</a></p><p>On the surface, it provisions a static website on AWS. But that’s not the real point. The real point is to show the same architecture three different ways:</p><ul><li>with <strong>L1 constructs</strong></li><li>with <strong>L2 constructs</strong></li><li>with <strong>L3 constructs</strong></li></ul><p>In other words, I wanted one repo that could answer a question I kept running into in practice:</p><blockquote><strong><em>When should I stay close to CloudFormation, when should I use the CDK sweet spot, and when should I lean on a higher-level pattern?</em></strong></blockquote><p>That question is much more interesting than “how do I host a website on AWS?”</p><p>In this article, I’ll walk through the repo the same way I designed it to be explored:</p><ul><li>First, what it actually builds</li><li>Then, how the repo is organized</li><li>Then, how does the app switch between L1, L2, and L3</li><li>and finally, how I’d recommend approaching it as a reader or contributor</li></ul><p>By the end, you should be able to open the repo and immediately understand what is going on.</p><h3>Why I built this repo</h3><p>I didn’t build this project because the internet needed one more “deploy a static website with S3 and CloudFront” tutorial.</p><p>I built it because I wanted a controlled comparison.</p><p>I wanted one architecture, one entry point, and three implementations:</p><ul><li>one that stays close to raw CloudFormation,</li><li>one that feels like idiomatic CDK,</li><li>and one that uses an opinionated pattern.</li></ul><p>That way, the differences are not theoretical. They are visible in code.</p><p>The architecture stays mostly the same.<br> What changes is the amount of abstraction, the amount of wiring I have to do myself, and the amount of intent the code reveals.</p><p>That’s what this repo is really about.</p><h3>What the repo deploys</h3><p>All three implementations target the same baseline architecture:</p><ul><li>a <strong>private S3 bucket</strong></li><li>a <strong>CloudFront distribution</strong></li><li><strong>Origin Access Control (OAC)</strong> between CloudFront and S3</li><li><strong>HTTPS redirection</strong></li><li><strong>SPA-friendly routing</strong> back to index.html</li></ul><p>That combination is the backbone of a modern static frontend on AWS. CloudFront documents OAC as the recommended way to secure S3 origins, and AWS documents CDK constructs in three layers: L1, L2, and L3.</p><p>So while the repo looks like a static website example, I think of it differently:</p><blockquote><em>It is a repo about </em><strong><em>architecture expressed through different CDK layers</em></strong><em>.</em></blockquote><p>That framing matters because it changes how you read the code.</p><h3>The repo is not three separate demos</h3><p>One thing I wanted to avoid was building three isolated examples that had nothing to do with one another.</p><p>So instead of creating three disconnected projects, I built <strong>one CDK app</strong> with <strong>one decision point</strong>.</p><p>At the center of the repo is this file:</p><p><a href="https://github.com/Mihankhahp/AWS-CDK-L1-L2-L3-static-site/blob/main/infrastructure/bin/infrastructure.js">infrastructure/bin/infrastructure.js</a></p><p>That file resolves the deployment context and chooses which implementation to instantiate:</p><ul><li>l1</li><li>l2</li><li>or l3</li></ul><p>So this is not:</p><ul><li>one repo for L1,</li><li>another repo for L2,</li><li>and another repo for L3</li></ul><p>It is one application with three interchangeable infrastructure paths.</p><p>That is what makes the comparison meaningful.</p><h3>The project structure I ended up with</h3><p>Here is the part of the repo that matters most:</p><pre>infrastructure/<br>├── bin/<br>│   └── infrastructure.js<br>├── lib/<br>│   ├── static-website-stack-L1.js<br>│   ├── static-website-stack-L2.js<br>│   └── static-website-stack-L3.js<br>├── test/<br>│   └── infrastructure.test.js<br>├── package.json<br>├── cdk.json<br>└── README.md</pre><p>This layout is intentionally simple.</p><p>If you’re opening the repo for the first time, I’d recommend reading it in this order:</p><ol><li>README.md</li><li>bin/infrastructure.js</li><li>lib/static-website-stack-L2.js</li><li>lib/static-website-stack-L1.js</li><li>lib/static-website-stack-L3.js</li></ol><p>That reading order reflects how I think the repo is easiest to understand.</p><p>The README tells you the goal.<br>The entry point tells you how the app behaves.<br><strong>L2 gives you the clearest practical implementation.<br></strong>L1 and L3 then show the lower and higher abstraction extremes.</p><h3>The one file that connects the entire repo</h3><p>If I had to point to the most important design decision in this project, it would be the entrypoint logic in bin/infrastructure.js.</p><p>This is the core idea:</p><pre>// Prefer context first, then env vars, then defaults<br>const stage = app.node.tryGetContext(&#39;stage&#39;) ?? process.env.STAGE ?? &#39;dev&#39;;<br>const version =<br>  app.node.tryGetContext(&#39;version&#39;) ?? process.env.VERSION ?? &#39;0.0.0&#39;;<br><br>const retainRaw =<br>  app.node.tryGetContext(&#39;retainPreviousVersion&#39;) ??<br>  process.env.RETAIN_PREVIOUS_VERSION ??<br>  &#39;false&#39;;<br>const retainPreviousVersion = String(retainRaw).toLowerCase() === &#39;true&#39;;<br><br>// Which layer to deploy: l1 | l2 | l3<br>const layerRaw =<br>  app.node.tryGetContext(&#39;layer&#39;) ?? process.env.CDK_LAYER ?? &#39;l3&#39;;<br>const layer = String(layerRaw).toLowerCase();</pre><p>I wanted the repo to be flexible without becoming complicated.</p><p>So I used a simple resolution order:</p><ol><li><strong>CDK context</strong></li><li><strong>environment variables</strong></li><li><strong>defaults</strong></li></ol><p>That lets me do things like this:</p><pre>cdk deploy -c stage=dev -c version=0.0.1 -c layer=l2</pre><p>Then the app switches on the selected layer:</p><pre>switch (layer) {<br>  case &#39;l1&#39;:<br>    new StaticWebsiteStackL1(app, stackId, commonProps);<br>    break;<br>  case &#39;l2&#39;:<br>    new StaticWebsiteStackL2(app, stackId, commonProps);<br>    break;<br>  case &#39;l3&#39;:<br>    new StaticWebsiteStackL3(app, stackId, commonProps);<br>    break;<br>  default:<br>    throw new Error(`Unknown layer &quot;${layer}&quot;...`);<br>}</pre><p>That switch statement is the spine of the repo.</p><p>It means I can keep the deployment contract stable while changing the abstraction model underneath.</p><h3>What changes between L1, L2, and L3</h3><p>The architecture doesn’t change much.</p><p>The layer does.</p><p>AWS defines CDK construct levels from low-level CloudFormation-backed resources up to higher-level abstractions and patterns.</p><p>In this repo, that looks like this.</p><h3>L1 — raw and explicit</h3><p>In lib/static-website-stack-L1.js, I use Cfn* resources directly.</p><p>That includes things like:</p><ul><li>s3.CfnBucket</li><li>s3.CfnBucketPolicy</li><li>cloudfront.CfnOriginAccessControl</li><li>cloudfront.CfnDistribution</li></ul><p>This version is closest to CloudFormation thinking.</p><p>I have to define more of the resource wiring myself, which makes it more verbose, but also more transparent.</p><h3>L2 — the practical middle</h3><p>In lib/static-website-stack-L2.jsI use higher-level CDK constructs such as:</p><ul><li>s3.Bucket</li><li>cloudfront.Distribution</li><li>S3BucketOrigin.withOriginAccessControl(...)</li></ul><p>For me, this is the most balanced implementation in the repo.</p><p>It still shows the architecture clearly, but it removes a lot of repetitive low-level work.</p><h3>L3 — a pattern with opinions</h3><p>In lib/static-website-stack-L3.jsI use:</p><pre>import { CloudFrontToS3 } from &#39;@aws-solutions-constructs/aws-cloudfront-s3&#39;;</pre><p>That pattern is documented by <a href="https://docs.aws.amazon.com/pdfs/solutions/latest/constructs/constructs.pdf">AWS Solutions Constructs</a> as provisioning a CloudFront distribution backed by S3 through OAC.</p><p>So in the L3 version, I’m not just writing fewer lines.<br> I’m accepting a pattern that already carries a set of best-practice assumptions.</p><p>That distinction becomes important later in the series.</p><h3>Why the architecture looks the way it does</h3><p>There are a few choices in this repo that were deliberate from day one.</p><h3>Private Bucket</h3><p>I did not want a public S3 bucket pretending to be “good enough.”<br> CloudFront should be the public entry point. S3 should stay private.</p><h3>OAC</h3><p>CloudFront recommends OAC for securing S3 origins, and Amazon S3’s static website guidance points readers toward CloudFront with OAC when they want to keep Block Public Access enabled.</p><p>That made OAC the right choice for this repo.</p><h3>Built-in SPA routing</h3><p>A lot of frontend apps need unknown paths to resolveindex.html, so I included 403 and 404 fallbacks in the CloudFront configuration.</p><p>That keeps the example realistic for modern frontend routing.</p><h3>I wanted version and stage to be metadata, not bucket identity</h3><p>One of the repo choices I’m happiest with is not forcing version semantics into the bucket name.</p><p>Bucket names are global, and changing physical names too eagerly usually creates more pain than value. So I kept versioning as deployment metadata and stack behaviour rather than turning it into brittle naming logic.</p><h3>How I’d recommend exploring the repo</h3><p>If you clone the project today, this is the path I’d suggest.</p><h3>Install dependencies</h3><pre>cd infrastructure<br>npm install</pre><h3>Bootstrap your environment if needed</h3><pre>cdk bootstrap</pre><p>AWS documents bootstrapping as the step that prepares an AWS environment for CDK deployments.</p><h3>Start with L2</h3><pre>cdk synth -c stage=dev -c version=0.0.1 -c layer=l2</pre><p>Then, when you are comfortable:</p><pre>cdk deploy -c stage=dev -c version=0.0.1 -c layer=l2</pre><p>I recommend L2 first because it is the easiest version to learn from without hiding the architecture.</p><p>After that, compare it with L3:</p><pre>cdk synth -c stage=dev -c version=0.0.1 -c layer=l3</pre><p>And only then go study L1 with the right mental model.</p><p>That sequence makes the differences much easier to appreciate.</p><h3>One small detail that matters more than it seems</h3><p>The repo also includes a GitHub Actions workflow that runs cdk synth.</p><p>That matters.</p><p>Because once I started thinking of this repo as more than a local experiment, I wanted template generation to become part of the feedback loop. Not just deployment.</p><p>That workflow is not the main story of this article, but it is part of the repo’s design philosophy:</p><ul><li>keep the implementations comparable,</li><li>keep the configuration explicit,</li><li>and validate early.</li></ul><p>We’ll come back to that in Part 5.</p><h3>Where the rest of the series goes from here</h3><p>I built this repo to make the abstraction trade-offs visible.</p><p>So the rest of the series follows that same path.</p><p>In Part 2, I’ll start with the implementation I consider the best practical baseline: <strong>L2</strong>.</p><p>That’s where the architecture is still obvious, the code is still readable, and the infrastructure doesn’t disappear behind too much abstraction.</p><p>Once that version is clear, the L1 and L3 implementations become much more interesting to study.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24cd866fb7b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shards, Streams, and Scale: DynamoDB’s Blueprint for Real-Time Success]]></title>
            <link>https://medium.com/@mihankhahp/shards-streams-and-scale-dynamodbs-blueprint-for-real-time-success-255d880f7b7b?source=rss-13c6173df1fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/255d880f7b7b</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[solution-architect]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Peyman Mihankhah]]></dc:creator>
            <pubDate>Sat, 27 Sep 2025 17:38:14 GMT</pubDate>
            <atom:updated>2025-09-27T17:38:14.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><ul><li>All changes for a given partition key in AWS DynamoDB are directed to the same shard, with strict ordering, deduplication, and an exactly-once delivery guarantee.</li><li>Shards auto-scale and split as throughput grows, without manual intervention.</li><li>By default, you can read the stream at up to twice the table’s provisioned write capacity.</li><li>Consuming the stream incurs no additional read cost.</li></ul><h3>Introduction</h3><p>Amazon DynamoDB Streams is a powerful change data capture(CDC) feature that allows organisations to react to database changes in near real-time. By streaming a time-ordered log of item-level modifications, DynamoDB Streams enables event-driven integration with other services without complex polling or scheduling. This capability is especially valuable for designing real-time architectures, as it provides a serverless “trigger” mechanism to decouple business logic from database writes. We will explore a high-level review of how DynamoDB Streams determines its sharding based on partition keys and how that affects design decisions.</p><h3>High-level value for Event-Driven Architect</h3><p>The best use case for partition-key-based sharding is event-driven architectures that demand strict in-order handling of events for each logical entity, such as per-user or per-order workflows, while still leveraging parallelism across independent keys.</p><p>Common patterns include triggering downstream Lambdas for notifications, building audit and compliance pipelines, driving cross-region replication or materialised views, indexing to search engines, and powering real-time analytics, all of which benefit from shard-level ordering for each partition key.</p><h3>Case Study</h3><p>A high-volume e-commerce platform experiences bottlenecks when processing spikes of orders for specific products and warehouses. This leads to increased latency, inconsistent inventory updates, and head‑of‑line blocking across product lines.</p><h3>Opportunity</h3><ul><li>Achieve per‑product parallelism to eliminate cross‑product delays.</li><li>Ensure strict ordering and near real‑time inventory consistency.</li><li>Reduce operational costs by minimising redundant database reads/writes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YJiQpLL05vzcDvW5Sx29jg.gif" /><figcaption>High-level architecture of an order management system using DynamoDB Stream | designed by Peyman Mihankhah</figcaption></figure><h3>High-Level Design Overview</h3><h3>Order Table</h3><p>The table uses a composite key &lt;SKU#WarehouseId&gt; as the Partition Key and &lt;UUID&gt; as the order ID as a Secondary Key. This grouping ensures that all changes for a given product in a specific warehouse stay isolated within a single shard, allowing one processor to handle all related updates. <em>By grouping orders this way, hot partitions are avoided and throughput scales predictably.</em></p><ul><li><em>By grouping orders this way, hot partitions are avoided and throughput scales predictably.</em></li><li><em>Ordering Service uses idempotency keys to de-dupe retries and prevent duplicate orders.</em></li></ul><p>*SKU stands for “stock keeping unit”, and it is a number (usually eight alphanumeric digits) that retailers assign to products to keep track of stock internally.</p><h3>Streams A &amp; Order handling</h3><p>Incoming order records are processed in batches based on a configured size or time window. Instead of handling each order with its own read and write (1 order → 1 read + 1 write), the system aggregates multiple orders into a single operation (N orders → 1 read + 1 write).</p><ul><li><em>This eliminates redundant calls, reduces DynamoDB pressure, and unlocks significant efficiency gains for high-volume order flows.</em></li><li><em>DLQs apply to all critical streams (A/B/C + payment) for visibility, retries, and monitoring.</em></li></ul><h3>Inventory Table</h3><p>All inventory updates are written with ACID-compliant transactions. Each transaction conditionally decrements InventoryQty only if sufficient stock is available (InventoryQty ≥ N).</p><ul><li>This prevents overselling even when multiple customers are buying the same item at once. For example, if two shoppers both try to grab the last unit, only one succeeds.</li><li>Inventory acts as the source of truth. Order_Table is eventually consistent and reconciled via stream-driven updates.</li></ul><h3>Stream B &amp; Consumption</h3><p>The most critical consumer is the Cache Updater, which updates in-memory stores (e.g., Redis) with the latest InventoryQty. This directly optimises high-throughput read workloads by reducing DynamoDB read pressure and enabling sub-millisecond access latency.</p><p>In parallel, Stream B powers other real-time consumers:</p><ul><li>Notifications (e.g., “Low Stock” or “Sold Out” alerts)</li><li>Analytics/Forecasting (feeding inventory trends to BI or ML pipelines)</li><li>Fulfilment Orchestration (triggering downstream logistics when inventory changes are confirmed)</li></ul><h3>Read Service</h3><p>The read service manages high-volume inventory lookups. It first checks the in-memory cache for the requested &lt;SKU#WarehouseId&gt;. If present, results are returned instantly. On a cache miss, the service performs a strongly consistent read from the Inventory_Table, then writes the result back into cache for future requests.</p><ul><li>This design delivers millisecond response times for customers while keeping DynamoDB read pressure under control.</li></ul><h3>Why DynamoDB Streams?</h3><ul><li>Each PartitionKey (SKU#WarehouseId) maps to a separate shard, enabling independent, concurrent processing for different products without interference.</li><li>Records within a shard maintain strict sequence, ensuring that the earliest orders are fulfilled first, accurately reflecting when a product sells out.</li><li>Native Lambda integration allows seamless, serverless consumption of change events, simplifying scalability as order volumes fluctuate.</li><li>Batching multiple updates into a single Lambda invocation minimises redundant reads/writes, lowering operational costs.</li><li>Lambda event source mapping supports automatic retries and integration with a Dead‑Letter Queue (DLQ), safeguarding against data loss.</li></ul><h3>Scale Illustration: Walmart Canada Example</h3><blockquote><a href="http://walmart.ca/"><em>Walmart.ca</em></a><em> is visited by more than 1.5 million customers daily, In fiscal year ended January 31, 2024, there were 403 Walmart retail stores in Canada, an increase compared to a year earlier.</em></blockquote><h3>Conversion Scenario</h3><p>Assumption: 100% of 1.5M daily visitors place an order within a 12-hour window (flash-sale style).</p><p>Total Orders (12h): <em>1,500,000 ÷ (12×3600) ≈ 34.7 orders/second</em></p><p>Per Branch Load (403 stores): <em>34.7 ÷ 403 ≈ 0.086 orders/second per branch</em></p><h3>Flash-Sale Surge (20×)</h3><p>During a peak promotion (e.g., Black Friday):</p><p>Orders per Branch: <em>0.086 × 20=1.72 orders/second</em></p><p>Write Capacity Units (WCU): 1.72WCU/s ⇒ 0.172% of 1,000 WCU capacity</p><p>Note: <em>1,000 WCU is the per-partition write throughput limit in DynamoDB, making it the standard reference point for assessing partition load.</em></p><h3>Trade‑offs &amp; Considerations</h3><ul><li>Latency vs. cost: Larger batch sizes reduce DynamoDB calls (lower cost) but can increase per‑record processing latency. Determine the right balance based on SLAs.</li><li>Partition key design: Using ProductId#WarehouseId ensures strict ordering but concentrates high‑volume keys into fewer shards. Consider splitting or re‑keying if a single product/warehouse pair experiences extreme traffic.</li><li>Error handling overhead: Integrating DLQs adds resilience but increases system complexity. Implement idempotency, monitoring, and alerting to manage failures effectively.</li></ul><h3>Why Not SQS FIFO with Deduplication and GroupId?</h3><p>At first glance, Amazon SQS FIFO queues seem like a natural fit for enforcing strict ordering and deduplication, since they provide both features natively via the MessageGroupId and DeduplicationId properties. However, there are important trade-offs that make DynamoDB Streams a better choice for change-data-capture and event-driven workflows directly tied to DynamoDB tables:</p><p>Native Coupling with DynamoDB Writes</p><ul><li>DynamoDB Streams captures changes as part of the database commit path, guaranteeing that every insert/update/delete produces a corresponding change record.</li><li>With SQS FIFO, you’d need additional application logic to publish every database change into the queue. This adds latency, potential failure points, and increases operational overhead.</li></ul><p>Exactly-Once, In-Order Delivery per Partition Key</p><ul><li>Streams ensures that all changes for the same partition key flow to a single shard with strict order and exactly-once delivery guarantees.</li><li>SQS FIFO ensures order within a MessageGroupId, but deduplication is time-window based (5 minutes) and does not provide the same exactly-once semantics. Retries can reintroduce duplicates that your consumer must handle.</li></ul><p>Throughput and Scalability</p><ul><li>DynamoDB Streams automatically scales shards as the underlying table grows. You do not provision or manage throughput for Streams.</li><li>FIFO queues are limited to 300 messages per second per message group (or 3,000 with batching). This is sufficient for some workloads, but it becomes a bottleneck for high-volume, multi-entity transactional systems.</li></ul><p>Cost and Redundancy</p><ul><li>Consuming DynamoDB Streams incurs no extra read cost, since it’s an extension of your DynamoDB write capacity.</li><li>With SQS FIFO, you pay per API call and per message, and you also duplicate writes: once to DynamoDB, once to the queue. That doubles both write traffic and error handling complexity.</li></ul><p>Operational Complexity</p><ul><li>Using Streams means you can connect Lambda directly as a trigger. AWS manages shard polling, scaling, retries, and checkpointing.</li><li>With SQS FIFO, you’d have to wire producer code, ensure deduplication, and manage consumer concurrency yourself.</li></ul><h3>DynamoDB Streams and Sharding by Partition Key</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCPLIRuEcjjevm8YzkWcsA.png" /><figcaption>Build Scalable, event-driven architectures with Amazon DynamoDB and AWS Lambda [ Lee Hannigan ]</figcaption></figure><p>Under the hood, DynamoDB tables are divided into storage partitions based on the hash (partition) key. Each partition manages a subset of items and has its own throughput capacity. DynamoDB Streams uses a shard for each storage partition to capture the changes happening on that partition. In essence, the partition key determines which shard an item’s change record goes to. All updates to items sharing the same partition key will appear in the same stream shard, preserving their relative order. This design guarantees that changes made to a single primary key will be preserved within a shard, allowing consumers to process changes for a given item or entity in the correct sequence.</p><p>Notably, a given partition (and its associated key values) will be present in at most one open shard at a time. Even if DynamoDB internally splits a busy partition for scaling, it creates new shards with a defined parent-child lineage, meaning an item’s key won’t be spread across multiple active shards concurrently.</p><p>This property simplifies consumer logic: your processing code can read each shard in order and inherently achieve per-item sequential consistency. DynamoDB Streams also ensures that each change record appears exactly once in the stream and is not duplicated (though consumers should still handle retry semantics, discussed later). Shards are ephemeral and scale automatically. As tables scale (e.g. adding partitions for capacity), DynamoDB will add shards. If a shard becomes too busy, it can split into multiple shards to increase throughput, with child shards continuing from where the parent left off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtPJSFvA6SzMgtno7Re2Vg.png" /><figcaption>Deep Dive into DynamoDB Stream and the Lambda Integration [Maurice Borgmeier]</figcaption></figure><p>This automatic sharding enables Streams to scale with the table’s workload without requiring manual intervention. The DynamoDB Streams log can be read at roughly double the rate of the table’s provisioned write capacity, underscoring its ability to keep up with high-velocity applications.</p><h3>More technical details?</h3><ul><li><a href="https://aws.amazon.com/blogs/database/build-scalable-event-driven-architectures-with-amazon-dynamodb-and-aws-lambda/">Build scalable, event-driven architectures with Amazon DynamoDB and AWS Lambda | Amazon Web Services</a></li><li><a href="https://medium.com/@joudwawad/dynamodb-streams-deep-dive-da64c2e5aa84">DynamoDB Streams Deep Dive</a></li></ul><h3>Reference:</h3><ul><li><a href="https://www.tecracer.com/blog/2022/03/deep-dive-into-dynamodb-streams-and-the-lambda-integration.html">Deep Dive into DynamoDB streams and the Lambda integration</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html">Change data capture for DynamoDB Streams</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/eventbridge-for-dynamodb.html">Integrating DynamoDB with Amazon EventBridge</a></li><li><a href="https://aws.amazon.com/blogs/aws/dynamodb-update-triggers-streams-lambda-cross-region-replication-app/">DynamoDB Update - Triggers (Streams + Lambda) + Cross-Region Replication App | Amazon Web Services</a></li><li><a href="https://www.newswire.ca/news-releases/walmart-canada-announces-additional-32-7-million-pay-investment-for-retail-and-health-associates-864318382.html">Walmart Canada announces additional $32.7 million pay investment for retail and health associates</a></li><li><a href="https://www.statista.com/statistics/539497/number-of-stores-walmart-canada/">Walmart stores Canada 2025| Statista</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=255d880f7b7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Imperative of Deep Personalization in the Age of Generative AI]]></title>
            <link>https://medium.com/@mihankhahp/the-imperative-of-deep-personalization-in-the-age-of-generative-ai-69cc55a6b15d?source=rss-13c6173df1fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/69cc55a6b15d</guid>
            <dc:creator><![CDATA[Peyman Mihankhah]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 23:18:34 GMT</pubDate>
            <atom:updated>2024-10-20T23:34:35.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EeCNUcIioXg-eMWN1aK8g.jpeg" /></figure><h3>Introduction</h3><p>In today’s digital age, connecting with customers on a personal level isn’t just a nice-to-have — it’s essential. With the rise of Generative Artificial Intelligence, businesses have a powerful tool to make these connections more meaningful and efficient than ever before. But how can we leverage this technology without losing the human touch?</p><p>Let’s dive into how deep personalization powered by generative AI can transform business communications and help us build stronger relationships with our audiences.</p><h3>Understanding GenAI and Its Impact on Business Communication</h3><p>Generative AI refers to a type of artificial intelligence that can create new content — such as text, images, or even music — by learning from existing data. Models like o1-preview have the remarkable ability to produce human-like text by its PhD-level reasoning.</p><h3>So, what does this mean for businesses?</h3><p>Generative AI allows for automated content creation at a scale and speed previously unattainable. It enables scalable personalization, where you can tailor messages to individual customers without spending countless hours crafting each one. This level of personalization enhances engagement, delivering content that resonates with your audience and leading to better relationships and more conversions.</p><p>But with great power comes great responsibility. As we embrace generative AI, we need to ensure we’re using it to enhance our communications, not hinder them.</p><h3>The Challenges in B2B Communication</h3><h4>Legacy Problems</h4><p>In the realm of B2B communication, businesses have long grappled with certain challenges. Traditionally, generic communication methods have fallen flat. Sending the same message to all prospects doesn’t engage them; it feels impersonal and often gets ignored. This lack of engagement means missed opportunities and wasted resources.</p><p>To counteract this, many companies have relied on SDRs to add a personal touch. However, using SDRs extensively has proven to be very costly and inefficient. Personalized outreach requires significant time and manpower, which isn’t always sustainable, especially for smaller organizations.</p><h4>New Problems</h4><p>With the advent of advanced technologies, new challenges have emerged. While generative AI offers the promise of personalization, it’s easy to fall into the trap of creating messages that lack the human touch. Messages might technically be personalized but still feel generic in tone and style, failing to truly connect with the recipient.</p><p>There’s also often a lack of reasoning and a clear point of contact in these messages. Without thoughtful context or a compelling reason for reaching out, messages can seem random or irrelevant.</p><p>Moreover, inaccuracies can creep into automated communications, leading to a lack of trust. If a message contains incorrect information or misrepresents the recipient’s needs, it not only fails to engage but can also damage the sender’s credibility.</p><p>These issues highlight the pressing need for a solution that combines efficiency with genuine personalization and accuracy.</p><h3>The Emergence of AI-Generated Spam</h3><p>We’ve all received those emails that start with our name and mention a few random words about us or our company, but quickly turn into generic sales pitches. This is the new wave of AI-generated spam. These messages might look personal but feel generic, as they use basic personalization without any depth. They’re ineffective and often annoying; recipients can easily spot these insincere messages and are likely to ignore or delete them.</p><p>Furthermore, these messages often lack a human touch, with tone and style that don’t resonate on a personal level. They may also miss a clear point of contact or reason for reaching out, leaving recipients confused about the message’s purpose.</p><p>To truly connect with our audience, we need to move beyond surface-level personalization and address these challenges directly.</p><h3>The Three-Layer Personalization Methodology</h3><p>To address these challenges, let’s explore the Three-Layer Personalization Methodology. This approach helps businesses achieve deep personalization using generative AI without overwhelming resources.</p><p>In brief with Personize Studio, you can build AI agents that represent you more accurately because of the above three layers of customization you can apply to perfect personalization to your customers</p><h4>First Layer: Company-Specific AI Personalization</h4><p>At the foundation of this methodology is tailoring AI models to reflect your brand’s unique voice and style. By feeding the AI agents with your company’s documents, style guides, and previous communications, you ensure that all generated content aligns with your brand identity. This process involves integrating company-specific language, tone, and messaging nuances into the AI agents.</p><p>For instance, if your brand has a casual and friendly tone, the AI should produce content that feels conversational and approachable. If your brand is more formal and professional, the AI should mirror that style. This alignment builds trust with your audience, as they receive consistent and authentic messages that resonate with your brand’s personality. Authenticity matters; when your communications feel genuine, your audience is more likely to engage and develop a positive association with your brand.</p><h4>Second Layer: Campaign and Ideal Customer Profile Alignment</h4><p>The second layer focuses on aligning messages with specific marketing campaigns and customer segments, often referred to as ICPs. This involves customizing content to match the goals and themes of your marketing efforts and tailoring messages to different segments of your audience.</p><p>By understanding your audience’s unique needs, pain points, and interests, you can adjust your messaging accordingly. For example, a campaign targeting small business owners might emphasize cost-effectiveness and scalability, while a campaign aimed at enterprise clients might focus on integration and robust features. Highlighting the benefits and solutions most relevant to each segment increases engagement by speaking directly to your audience’s needs. It also improves conversion rates by providing relevant solutions and strengthens relationships by showing that you genuinely understand and care about your customers.</p><h4>Third Layer: Advanced Lead Enrichment and Personalization</h4><p>The final layer involves diving deep into individual personalization by enriching your data using both internal and external sources. Internal resources like CRM data and past interactions provide valuable insights into your existing relationship with the lead — their purchase history, previous communications, and preferences. External information, such as recent news about the lead’s company, or industry trends, can offer additional context.</p><p>With this enriched data, you can craft personalized messages that reference specific achievements, challenges, or events relevant to the recipient. For example, acknowledging a recent award their company received or addressing a current challenge in their industry shows that you’ve done your homework. By offering solutions tailored to their role and responsibilities, you create meaningful connections that differentiate your communication from competitors. This level of personalization significantly boosts response rates, as recipients feel genuinely understood and valued.</p><p>By implementing the Three-Layer Personalization Methodology, businesses can overcome the challenges of generic communication and the inefficiencies of traditional personalization methods. This approach ensures that every message is infused with your brand’s unique voice, aligned with your strategic goals, and deeply personalized to resonate with each individual recipient.</p><h3>How This Methodology Solves the Personalization Paradox</h3><p>Implementing this three-layer approach addresses both legacy and new problems in B2B communication.</p><ul><li>Efficiency without High Costs: By automating personalization through AI that’s been tailored to your company’s voice and strategies, you reduce your SDRs’ research time while maintaining a high level of personalization.</li><li>Enhanced Human Touch: Customizing the AI with your brand’s tone and style ensures that messages feel personal and genuine, overcoming the lack of human touch in generic AI communications.</li><li>Clear Reasoning and Points of Contact: Aligning messages with specific campaigns and customer profiles provides clear context and purpose, making communications more relevant and engaging.</li><li>Improved Accuracy and Trust: Deep lead enrichment ensures that messages are accurate and tailored to the recipient, building trust and demonstrating that you understand their needs.</li></ul><p>By focusing on authentic, tailored communications, businesses can overcome the personalization paradox, ensuring that their outreach efforts are both efficient and effective.</p><h3>Personize Studio: Bringing Personalization to Life</h3><p>To make this approach accessible, Personize Studio offers a platform that seamlessly implements the Three-Layer Personalization Methodology, catering to users of all technical backgrounds.</p><h4>What Is Personize Studio?</h4><p>Personize Studio is a user-friendly, no-code platform designed to help businesses achieve deep personalization at scale. It allows you to:</p><ul><li>Customize AI Models: Reflect your brand voice and style using company-specific data.</li><li>Align Communications: Tailor messages to specific campaigns and Ideal Customer Profiles (ICPs).</li><li>Enrich Lead Data: Leverage both internal resources and external public information to enhance personalization.</li></ul><h4>Features for Non-Technical Users</h4><p>Understanding that not all users are AI experts, Personize Studio provides optimized pre-built agents for the most common use cases. These agents can be easily added to a run, requiring only a one-time mapping of data points. This means you can achieve advanced personalization without needing technical expertise, making the process efficient and straightforward.</p><h4>Advanced Personalization for AI Enthusiasts</h4><p>For advanced users and AI enthusiasts, Personize Studio offers additional capabilities:</p><ul><li>API Product and SDK: We are introducing our API and SDK very soon, providing advanced users with the tools to build custom solutions and integrate Personize Studio into their existing workflows.</li><li>HubSpot Workflow Action: Our HubSpot Workflow Action Alpha version has been released recently, enabling seamless integration with HubSpot to automate and personalize communications directly within your CRM.</li></ul><p>Whether you’re new to AI or an expert, Personize Studio empowers you to achieve the level of personalization you need. By offering tools and features suitable for all skill levels, we make advanced personalization accessible and manageable for everyone.</p><h3>Conclusion</h3><p>In a world overflowing with generic messages, standing out requires a personal touch. By embracing deep personalization through generative AI and implementing the Three-Layer Personalization Methodology, we can create communications that not only reach our audience but truly resonate with them.</p><p>With Personize Studio, you can build AI agents that represent you more accurately because of the above three layers of customization you can apply to perfect personalization to your customers and empower your businesses to bridge the gap between automation and authenticity, ensuring every message counts. It’s about making connections that matter, fostering trust, and building lasting relationships.</p><p>Ready to transform your communications? Let’s make personalization meaningful again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69cc55a6b15d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>