<?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 Jason Conway-Williams on Medium]]></title>
        <description><![CDATA[Stories by Jason Conway-Williams on Medium]]></description>
        <link>https://medium.com/@jcdubs?source=rss-9821838c8468------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*18rXNOXL0Eyzl86rplHaAA.jpeg</url>
            <title>Stories by Jason Conway-Williams on Medium</title>
            <link>https://medium.com/@jcdubs?source=rss-9821838c8468------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:49:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jcdubs/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[ Handling Cross-Region SSM Parameters in AWS CDK]]></title>
            <link>https://jcdubs.medium.com/handling-cross-region-ssm-parameters-in-aws-cdk-52cc0be56145?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/52cc0be56145</guid>
            <category><![CDATA[parameter-store]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws-ssm]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 11:49:02 GMT</pubDate>
            <atom:updated>2026-03-26T11:49:02.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_9hgF8oI_Ri1vID_Rhepg.png" /></figure><p>I recently worked on a CDK solution where the main resources were deployed in eu-west-2, including a Route 53 hosted zone and a CloudFront distribution. Because CloudFront requires its ACM certificate to be created in us-east-1, I had to provision the certificate in that region instead of alongside the rest of the stack.</p><p>I also wanted to make this CloudFront distribution reusable across other projects in the organisation, so the certificate ARN needed to be shared with stacks owned by different teams and deployed in different regions. To make that possible, I stored the certificate ARN in AWS Systems Manager Parameter Store.</p><p>The challenge is that Parameter Store values are regional. If a stack deployed in eu-west-2 tries to look up a parameter that exists only in us-east-1, CDK will fail with an error saying the parameter cannot be found. In other words, the stack performing the lookup must be operating in the same region as the parameter.</p><p>To solve this, I moved the parameter lookup into the bin entry file and created inline stacks specifically for resolving cross-region values. When calling StringParameter.valueFromLookup, I make sure the inline stack used for the lookup is configured for the same region as the parameter itself. This allows the parameter to be resolved correctly and then passed into the stacks that need it.</p><pre>const account = process.env.CDK_DEFAULT_ACCOUNT;<br><br>// Create an inline stack in the eu-west-2 region for SSM lookups.<br>const ssmLookupEuWest2 = new cdk.Stack(app, &#39;PlatformBackendSsmLookupEuWest2&#39;, {<br>  env: { account, region: &#39;eu-west-2&#39; },<br>  description: &#39;Platform Backend: SSM parameter lookups (eu-west-2)&#39;,<br>});<br><br>// Create an inline stack in the us-east-1 region for SSM lookups.<br>const ssmLookupUsEast1 = new cdk.Stack(app, &#39;PlatformBackendSsmLookupUsEast1&#39;, {<br>  env: { account, region: &#39;us-east-1&#39; },<br>  description: &#39;Platform Backend: SSM parameter lookups (us-east-1)&#39;,<br>});<br><br>// Retrieve the parameter from eu-west-2 using the ssmLookupEuWest2 inline stack.<br>const hostedZoneName = ssm.StringParameter.valueFromLookup(<br>  ssmLookupEuWest2,<br>  `/platform-central/${config.domainName}/hosted-zone-name`,<br>);<br><br>// Retrieve the parameter from us-east-1 using the ssmLookupUsEast1 inline stack.<br>const certificateArnLookup = ssm.StringParameter.valueFromLookup(<br>  ssmLookupUsEast1,<br>  `/platform-central/${config.domainName}/wildcard-cert-arn`,<br>);</pre><p>The only real downside with this approach is that it creates an empty CloudFormation stack just for the parameter lookup.</p><p>That might be fine for some people, but I really didn’t like it. Creating empty stacks just makes the CloudFormation console messier, and it felt like a workaround I didn’t really want hanging around.</p><p>So instead, I went with another option: creating a copy of the parameter in the second region from the bin entry file, like this:</p><pre>const app = new cdk.App();<br>const account = process.env.CDK_DEFAULT_ACCOUNT;<br>const domainName = &#39;develop.example.com&#39;;<br><br>// We create the DNS stack first in the eu-west-2 region.<br>const dnsStack = new LipsPlatformCentralDNSStack(app, &#39;PlatformCentralDNSStack&#39;, {<br>  env: { account, region: &#39;eu-west-2&#39; },<br>  crossRegionReferences: true,<br>  description: &#39;Platform Central: Route53 Hosted Zones&#39;,<br>  zoneName: domainName,<br>});<br><br>// We then create the certificate stack in the us-east-1 region.<br>const certStack = new PlatformCentralCertStack(app, &#39;PlatformCentralCertStack&#39;, {<br>  env: { account, region: &#39;us-east-1&#39; },<br>  crossRegionReferences: true,<br>  description: &#39;Platform Central: Wildcard ACM Certificate (us-east-1)&#39;,<br>  domainName,<br>  hostedZoneId: dnsStack.hostedZoneId,<br>  hostedZoneName: domainName,<br>});<br><br>certStack.addDependency(dnsStack);<br><br>// We create the auth stack in the eu-west-2 region.<br>const authStack = new PlatformCentralAuthStack(app, &#39;PlatformCentralAuthStack&#39;, {<br>  env: { account, region: &#39;eu-west-2&#39; },<br>  crossRegionReferences: true,<br>  description: &#39;Platform Central: Cognito Authentication&#39;,<br>  domainName,<br>});<br>authStack.addDependency(certStack);<br><br>/** <br>* Finally, we use the auth stack created in the eu-west-2 region<br>* as the scope when creating the WildcardCertArnParam parameter to<br>* ensure the paramter is also available in the eu-west-2 region.<br>*/<br>new ssm.StringParameter(authStack, &#39;WildcardCertArnParam&#39;, {<br>  parameterName: `/platform-central/${domainName}/wildcard-cert-arn`,<br>  stringValue: certStack.certificateArn,<br>  description: `Wildcard certificate ARN for *.${domainName}`,<br>});</pre><p>This means the certificate ARN parameter ends up existing in both us-east-1 and eu-west-2, so stacks deployed in eu-west-2 can read it without any issues.</p><p>Both approaches get around the fact that Parameter Store is regional, but neither is perfect. If you are happy to create an empty stack just to do the lookup, the first approach works well enough. If that feels a bit messy, but you are okay with duplicating parameters across regions, then the second approach is probably the better fit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52cc0be56145" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Janus : Self-Contained Serverless Authorisation with Cedar ]]></title>
            <link>https://jcdubs.medium.com/introducing-janus-self-contained-serverless-authorisation-with-cedar-5221420dbd31?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/5221420dbd31</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[authorisation]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 10:20:37 GMT</pubDate>
            <atom:updated>2026-01-12T10:20:37.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*sKIN8FVLahtknOgPhcAuFg.jpeg" /></figure><h3>Introduction</h3><p>In a <a href="https://medium.com/@jcdubs/serverless-granular-authorisation-with-cedar-high-control-minimal-cost-1149640f8cd9">previous blog post</a>, I introduced a serverless architectural pattern for implementing fine-grained authorisation using the Cedar policy language. The setup uses a bunch of serverless building blocks: S3 as a central store for policies, a Lambda layer that exposes the Cedar decision engine via the Cedar WASM package from the Cedar project, and a small SDK that wraps all of this up into something easy to use.</p><p>The main motivation behind this pattern was to use Cedar as the authorisation engine and take advantage of everything it offers. That includes a clean separation of concerns with policies and schemas defined in their own files, fast and straightforward decision-making via the Cedar engine, and policies that are easy to read and manage as a human. On top of that, it’s a pattern that won’t break the bank — especially when you compare it to alternatives like Amazon Verified Permissions, which I showed in the previous article can end up costing more than the service it’s protecting.</p><p>Today I’m excited to announce the release of the <a href="https://www.npmjs.com/package/@jcdubs/janus">@jcdubs/janus npm package</a> 🎉.</p><p>It provides a set of reusable CDK constructs and SDK components that implement a more refined version of the serverless authorisation pattern I introduced earlier.</p><h3>Revisions to the original pattern</h3><p>Since the original blog post was published I’ve contemplated the architectural decisions at the core of the pattern. Specifically the use of a central policy store and providing the Cedar policy WASM package as a shared Lambda layer. I believe an improved version of this pattern would involve providing these two elements within the deployed Lambda code and environment.</p><p>Although these architectural changes mean you now need to release your service to roll out authorisation schema or policy updates, the benefits outweigh the downsides.</p><p>Being able to tweak policies and schemas without a deployment does give you a more loosely coupled code and authorisation setup, but tying those changes to a Git-based release process also brings some real advantages. You get proper quality gates, CI/CD checks, and a clear audit trail of who changed what and when.</p><p>That said, this isn’t the end of the road. Future versions of <strong>@jcdubs/janus</strong> may support multiple policy and schema loading strategies, letting you choose between the local Lambda file system, a central store, or even an HTTP endpoint. For now, though, Janus keeps things simple and only supports loading policies and schemas from the Lambda file system.</p><p>To that end, the @jcdubs/janus project provides two components to fulfil the newly revised pattern.</p><h4>Auth Lambda CDK Construct</h4><p>The AuthLambda is a level 3 CDK construct built on top of the level 2 Node.js Lambda construct. Unlike many level 3 constructs, which usually hide a lot of configuration and opinionated defaults, AuthLambda deliberately doesn’t do that. Instead, it expects you to supply all the usual configuration you’d provide to the underlying Node.js construct, but adds some smart bundling logic on top. This bundling step makes sure the Cedar WASM package, along with your Cedar policy and schema files, are included in the Lambda’s file system when the function is built.</p><h4>Janus SDK</h4><p>The SDK that comes with Janus is largely the same as the one I showed in the original blog post, with just a couple of architectural tweaks. Even though the Cedar WASM package is now provided via the Lambda file system rather than a shared Lambda layer, this change doesn’t affect how the SDK works. From the SDK’s point of view, Cedar is still loaded as a normal Node.js package import.</p><p>The bigger change is around how policies and schemas are loaded. The Janus SDK no longer pulls these from a central S3 policy store. Instead, your Cedar policy and schema files live directly on the Lambda file system and are loaded locally. These are then used by the Janus SDK services to decide whether the user making a request is authorised to perform a given action on a particular resource.</p><p>This change results in a more self-contained Lambda service, with authorisation bundled alongside it, and reduces the number of AWS resources and cross-service IAM permissions needed overall.</p><h3>Where can you find the Janus project</h3><p>The @jcdubs/janus project has been published to the <a href="https://www.npmjs.com/package/@jcdubs/janus">public npm repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*yArymNTwkJbex6s4jcc1Ng.png" /></figure><p>The project is fully open source and available on <a href="https://github.com/JCDubs/Janus">GitHub</a>, so feel free to dig in, explore the code, or contribute.</p><h3>Examples</h3><p>The project includes an examples directory with a sample <a href="https://github.com/JCDubs/Janus/tree/main/examples/order-service">Order service CRUD API</a>, along with a granular Cedar schema and policy that enforce access permissions based on users, groups, and resource state. The example shows how to build Lambda functions using the AuthLambda CDK construct, and how to use the Janus SDK to implement resource-based authorisation and the entity builder needed to evaluate Cedar policies.</p><h3>Contributing</h3><p>The project includes clear guidance on how to get involved, and contributions are very welcome. You’ll find details on how to contribute and how to conduct yourself when doing so in the <a href="https://github.com/JCDubs/Janus/blob/main/CONTRIBUTING.md">contributing</a> and <a href="https://github.com/JCDubs/Janus/blob/main/CODE_OF_CONDUCT.md">code of conduct</a> markdown files included in the repository.</p><h3>Future changes</h3><p>I’ve already mentioned one possible future improvement around how the project loads Cedar policy and schema files, but there are loads of other ideas I’d like to explore as well. These range from better policy and schema authoring support through to validation tooling, just to name a couple. I’m keen to hear ideas from the community too, so feel free to suggest improvements or new features by raising an issue on the project’s GitHub issues page and getting involved.</p><h3>In closing</h3><p>Im extremely excited to announce the release of @jcdubs/janus project and look forward to collaborating with our community to improve and enhance the project. While the project is new and in it’s infancy, it’s backed by a strong and proven authorisation engine and policy language provided by the Cedar project. Feel free to fork the repo and get involved 🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5221420dbd31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ You Don’t Need Ordered Events, You Need Smart Events ]]></title>
            <link>https://jcdubs.medium.com/you-dont-need-ordered-events-you-need-smart-events-f9eaf9be7186?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9eaf9be7186</guid>
            <category><![CDATA[eda]]></category>
            <category><![CDATA[sns]]></category>
            <category><![CDATA[aws-eventbridge]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Thu, 30 Oct 2025 09:13:47 GMT</pubDate>
            <atom:updated>2025-10-30T09:13:47.873Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y30WOgB1IyXpAgSqnM9u8Q.png" /></figure><p>Event-driven architectures often spark heated discussions about event ordering. Teams worry that if events don’t arrive in the right sequence, downstream systems will fall apart or store inconsistent data. This mindset often leads developers to over-engineer producers, enforce strict ordering, or even choose services like SNS FIFO topics purely for that guarantee.</p><p>But here’s the truth: producers don’t need to provide ordered events to be good citizens in an event-driven ecosystem. What they <em>do</em> need to provide are the right contextual properties — things like version numbers, updatedAt timestamps, and entity identifiers that allow consumers to determine event freshness and consistency on their own.</p><p>This is where understanding the difference between Amazon SNS and Amazon EventBridge becomes critical. SNS can offer ordered delivery through FIFO topics, but EventBridge, AWS’s event bus service designed for decoupled, scalable, and multi-account systems, does not. And that’s okay. EventBridge is still the better choice for most event-driven systems because ordering is not a producer’s responsibility. It is the consumer’s responsibility to reason about event state, and not every consumer will care about ordering. The producer’s job is to provide enough information in the event payload to enable consumers to enforce ordering when they need it.</p><p>In this post, we’ll explore:</p><ul><li>🔄 The difference between ordered and unordered event delivery</li><li>🏗️ Why EventBridge is the right tool for modern event-driven systems</li><li>🧾 How to design event payloads that empower consumers to handle ordering</li><li>🕒 How atomic database versioning or timestamps make unordered events safe and predictable</li></ul><p>By the end, you’ll see that unordered doesn’t mean unreliable — it means <em>decoupled, scalable, and smart</em> 💡.</p><h3>🧩 Designing Smart Events</h3><p>Smart events are self-contained, descriptive, and version-aware. They give consumers the context they need to reason about state without requiring the producer to guarantee delivery order.</p><p>Instead of thinking about events as a sequence to preserve, think of them as state updates with intent. A good event carries enough information for a consumer to determine what happened, when it happened, and how recent that information is.</p><p>Here is an example of a well-structured event:</p><pre>{<br>  &quot;entityId&quot;: &quot;user-123&quot;,<br>  &quot;version&quot;: 5,<br>  &quot;updatedAt&quot;: &quot;2025-10-29T10:15:00Z&quot;,<br>  &quot;eventType&quot;: &quot;UserUpdated&quot;,<br>  &quot;source&quot;: &quot;user-service&quot;,<br>  &quot;data&quot;: {<br>    &quot;name&quot;: &quot;Alice&quot;,<br>    &quot;email&quot;: &quot;alice@example.com&quot;<br>  }<br>}</pre><h4>🧱 Key properties to include</h4><p><strong>entityId</strong> identifies the subject of the event.</p><p><strong>version</strong> is a monotonically increasing number that reflects the version of the entity or aggregate.</p><p><strong>updatedAt</strong> is an ISO 8601 timestamp representing when the change occurred.</p><p><strong>eventType</strong> describes the nature of the change such as UserCreated or UserUpdated.</p><p><strong>source</strong> indicates where the event originated, which is useful in multi-domain environments.</p><p><strong>data</strong> contains the actual state change details.</p><p>When these properties are present, consumers can determine whether an event is new, duplicate, or stale, even if it arrives late or out of order.</p><h4>⚙️ The producer’s responsibility</h4><p>The producer does not need to ensure ordered delivery. Its job is to publish events that accurately represent state transitions, with consistent versioning and timestamps. This allows every consumer to implement its own logic for ordering, idempotency, and conflict resolution.</p><p>In practice:</p><ul><li>Increment the version each time an entity changes.</li><li>Use atomic updates in the database to prevent version conflicts.</li><li>Always publish the latest known version in the event payload.</li></ul><p>By focusing on clarity of data rather than sequence of delivery, you make your event-driven system more resilient, scalable, and easier to evolve over time.</p><h3>🗄️ Managing versioning and timestamps in DynamoDB</h3><p>Databases such as Amazon DynamoDB make it simple to manage version control and timestamps at the data layer.</p><p>Each item can include an atomic version number that is incremented on every write. When you perform an update, DynamoDB can check that the stored version matches the expected version before applying the change. If another process has already updated the record, the condition fails and the write is rejected.</p><p>This ensures that only one process successfully updates the record for a given version, which prevents race conditions and guarantees atomicity.</p><p>A typical pattern looks like this:</p><ul><li>Store a version attribute in each item.</li><li>Use a ConditionExpression that checks version = :expectedVersion before writing.</li><li>On success, increment the version to the next value.</li><li>On conflict, retry or discard based on your event logic.</li></ul><p>In addition, DynamoDB supports ISO 8601 timestamps for fields such as createdAt and updatedAt. These properties help track when the record was created and last updated, and they can also be used to determine event freshness or time-based ordering. ISO 8601 strings sort correctly in lexicographical order, which makes them easy to compare and query.</p><p>By combining an atomic version attribute with createdAt and updatedAt timestamps, your data model can naturally support unordered event delivery while maintaining consistency across producers and consumers.</p><h3>🧭 Consumer-Driven Ordering</h3><p>Once producers provide smart events with versioning and timestamps, the responsibility for ordering moves to the consumer. Each consumer can decide how much ordering logic it actually needs. Some may care deeply about sequence, while others may only care about the latest known state.</p><p>The goal for a consumer is simple: store or process the most recent version of the data.</p><h4>🧩 Handling versioned events</h4><p>When a consumer receives an event, it should check whether the incoming version is newer than what it already knows. If it is newer, the consumer updates its state. If it is older or equal, the event is ignored.</p><p>Here is a simple example of that logic:</p><pre>if (incoming.version &gt; stored.version) {<br>  updateRecord(incoming)<br>}</pre><p>This approach removes the need for ordered delivery because each event is self-describing. Even if events arrive out of order, consumers can safely process them based on version or timestamp.</p><h4>🗄️ Ensuring atomic updates</h4><p>When the consumer stores processed data, it should protect against race conditions and stale writes. In AWS, this is often achieved with conditional writes.</p><p>For example, with DynamoDB you can use a ConditionExpression to update the record only if the stored version is lower than the incoming one:</p><pre>await dynamoDb.update({<br>  TableName: &quot;Users&quot;,<br>  Key: { entityId: incoming.entityId },<br>  UpdateExpression: &quot;SET #data = :data, #version = :version&quot;,<br>  ConditionExpression: &quot;attribute_not_exists(#version) OR #version &lt; :version&quot;,<br>  ExpressionAttributeNames: {<br>    &quot;#data&quot;: &quot;data&quot;,<br>    &quot;#version&quot;: &quot;version&quot;<br>  },<br>  ExpressionAttributeValues: {<br>    &quot;:data&quot;: incoming.data,<br>    &quot;:version&quot;: incoming.version<br>  }<br>})</pre><p>If the condition fails, it means the record is already at a newer version, so the update is safely skipped.</p><h4>🕒 Using updatedAt for ordering and consistency</h4><p>Another reliable way to manage event freshness is to use the updatedAt property.</p><p>Since updatedAt timestamps are produced by the source of truth, consumers can rely on them to ensure that only newer updates are written to their database.</p><p>When using DynamoDB, this can be implemented with a conditional update that only succeeds if the incoming event’s updatedAt value is greater than what is already stored. ISO 8601 timestamps compare correctly as strings, which makes this pattern simple and safe to apply.</p><p>Here is an example in TypeScript using the AWS SDK v3:</p><pre>await ddb.send(new UpdateCommand({<br>    TableName: &quot;Users&quot;,<br>    Key: { entityId: incoming.entityId },<br>    UpdateExpression: &quot;SET #data = :data, #updatedAt = :updatedAt&quot;,<br>    ConditionExpression: &quot;attribute_not_exists(#updatedAt) OR :updatedAt &gt; #updatedAt&quot;,<br>    ExpressionAttributeNames: {<br>      &quot;#data&quot;: &quot;data&quot;,<br>      &quot;#updatedAt&quot;: &quot;updatedAt&quot;,<br>    },<br>    ExpressionAttributeValues: {<br>      &quot;:data&quot;: incoming.data,<br>      &quot;:updatedAt&quot;: incoming.updatedAt,<br>    },<br>  }));</pre><p>If the condition fails, DynamoDB throws a ConditionalCheckFailedException, which indicates that the stored record is already newer. The consumer can safely catch this exception and skip the update.</p><p>This ensures data consistency even if multiple events for the same entity arrive out of order.</p><h4>🧠 Different consumers, different needs</h4><p>Not all consumers care about ordering.</p><ul><li>A search index might only want the latest state.</li><li>An audit service might store every event, regardless of order.</li><li>A notification service might only care about certain event types.</li></ul><p>By making consumers responsible for ordering, each can choose the logic that fits its use case without forcing the producer or event bus to manage delivery guarantees.</p><p>This approach scales better, simplifies producer logic, and aligns perfectly with the decoupled nature of modern event-driven architectures.</p><h3>🏗️ Why EventBridge Wins</h3><p>Now that we have established how smart events and consumer-driven ordering work, it is important to consider the platform that carries those events. Many teams assume that ordered delivery is essential and immediately reach for SNS FIFO topics. While FIFO topics have their place, they come with trade-offs that often limit scalability and flexibility.</p><h4>🔍 Comparing Amazon SNS and Amazon EventBridge</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*RxKP9HxjCiTKOpw7Zzg50g.png" /></figure><h4>⚙️ Understanding the trade-offs</h4><p>SNS FIFO provides strict ordering within a message group, but each group is serialised, which significantly limits throughput. As your event volume grows, this creates a scaling bottleneck. FIFO topics also require publishers to define a message group ID and maintain it consistently, which increases complexity.</p><p>SNS Standard provides massive throughput but does not guarantee ordering or exactly-once delivery. It is fast and simple but not suitable for systems that rely on ordered delivery or complex routing logic.</p><p>EventBridge, on the other hand, focuses on flexibility, decoupling, and event intelligence rather than delivery guarantees. It allows you to define detailed event patterns, route events to multiple targets, and manage event schemas in a centralized way. EventBridge also supports cross-account and cross-region delivery, which is ideal for large distributed systems.</p><p>While SNS is best suited for point-to-point or simple fan-out messaging, EventBridge is designed for event-driven ecosystems that involve multiple services, domains, or even accounts.</p><h4>🧠 The takeaway</h4><p>If your architecture depends on ordering, you can use SNS FIFO or SQS FIFO for those narrow use cases. But for most modern, distributed applications, EventBridge provides the right level of abstraction and flexibility.</p><p>By designing events with properties such as version, updatedAt, and entityId, you remove the need for strict delivery order and gain all the benefits of EventBridge’s scalability, routing, and ecosystem integration.</p><p>EventBridge wins because it shifts focus from <em>message delivery</em> to <em>event understanding</em>. Instead of asking “<em>in what order did this arrive</em>,” consumers can ask “<em>what is the latest truth of this entity,</em>” which is the question that truly matters.</p><h3>⏱️ When Ordering Still Matters</h3><p>Although most systems can rely on unordered, smart events, there are still scenarios where ordering is essential. In these cases, the sequence of events represents more than just state changes — it defines the meaning of the data itself.</p><p>A good example is financial transactions. If two operations are processed in the wrong order, the resulting balance or ledger state could be incorrect. Similarly, audit logs, workflow systems, or event sourcing patterns often depend on the exact sequence of events to replay or reconstruct history accurately.</p><p>In situations like these, using a service that guarantees ordered delivery can be appropriate. SNS FIFO topics or SQS FIFO queues provide strict message ordering within a defined message group and can ensure that each message is processed in sequence. However, these solutions introduce trade-offs such as:</p><ul><li>Lower throughput due to message group serialisation</li><li>Higher coupling between producers and consumers</li><li>Increased complexity in scaling and partitioning workloads</li></ul><p>When ordering is truly required, use these tools for narrow, well-defined boundaries rather than across your entire system. For example, a payment processing component might use an SQS FIFO queue to maintain transaction order, while the rest of the platform communicates through EventBridge for flexibility and scale.</p><p>Even in these cases, it is still valuable to include metadata such as version and updatedAt in your events. These properties provide additional safeguards and allow consumers to validate consistency in case of replays, retries, or duplicate deliveries.</p><p>The key is to make ordering an explicit design choice, not a default assumption. Most domains can function perfectly with unordered events, as long as producers provide enough context for consumers to reason about event freshness and consistency.</p><p>By using ordering only where it truly matters, you avoid unnecessary complexity while maintaining correctness where it counts.</p><h3>💡 Conclusion: Be a Smart Publisher</h3><p>Not providing ordered events does not make you a bad publisher. What matters is giving consumers a clear way to determine order on their own. A poor publisher sends events that leave consumers guessing. A good publisher designs events that are self-describing and make it easy for others to reason about state and consistency.</p><p>Teams should aim to be good publishers by:</p><ul><li>Including clear, consistent metadata such as version, updatedAt, and entityId in every event.</li><li>Maintaining reliable patterns for how events represent state transitions.</li><li>Documenting how these properties work and how consumers can use them to implement ordering, idempotency, and freshness checks.</li><li>Providing shared libraries or tooling that standardise event publishing and consumption across services.</li></ul><p>Being a good publisher is about creating clarity, not control. The goal is to empower consumers with enough information to make their own decisions about ordering and consistency. When publishers take responsibility for clear event design and good documentation, and consumers take responsibility for handling order and state, the result is a system that is both scalable and dependable.</p><p>In the end, unordered does not mean unreliable. It means your system is decoupled, event-driven, and built on the foundation of smart events that give consumers everything they need to do their job correctly, no matter when those events arrive.</p><p>You do not need ordered events. You need smart events 🧠.</p><p>Thanks for taking the time to read 🙏. I hope this gives you a clearer way to think about event-driven design and helps your team build systems that are smarter, more consistent, and easier to scale.</p><p>If you’ve tackled similar challenges with unordered events or have your own patterns for handling consistency, I’d love to hear about them. Drop a comment — Happy building! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9eaf9be7186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Introducing Cloud Blocks: Open Source, Reusable, Production-Grade CDK Constructs ]]></title>
            <link>https://medium.com/on-tech-by-leighton/introducing-cloud-blocks-open-source-reusable-production-grade-cdk-constructs-fdc102f5ca8d?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdc102f5ca8d</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 13:49:52 GMT</pubDate>
            <atom:updated>2025-09-30T13:49:52.359Z</atom:updated>
            <content:encoded><![CDATA[<h4>An open source project from the AWS teams at Leighton</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4vUmXy-kRioxKVa_emAew.png" /></figure><p>In modern cloud-native teams, one of the friction points is reinventing the same foundational building blocks over and over — networking, observability, API gateways, security, etc. What if your teams didn’t need to start from scratch each time, but instead got a reliable, battle-tested set of infrastructure primitives to plug into?</p><p>That’s what Cloud Blocks is all about. It’s an open-source library of L3 AWS CDK constructs that encapsulates opinionated best practices for infrastructure — helping developers and internal teams stand up secure, consistent, and production-ready stacks faster.</p><p>With Cloud Blocks, you can:</p><ul><li>🧱 Leverage well-designed, reusable building blocks rather than hand-crafting boilerplate</li><li>🔒 Adopt standardised best practices in networking, security, observability, and deployments</li><li>⚡ Reduce errors, drift, and duplication across projects</li><li>🚀 Ramp up new teams or initiatives with infrastructure primitives that already <em>“just work”</em></li></ul><p>We built this for ourselves — to scale CDK adoption across multiple teams at Leighton Digital — and now we’re excited to open it up to the community. In this post, we’ll walk through what Cloud Blocks offers, how it’s structured, and how you can get started using (and contributing to) it today.</p><h3>What Cloud Blocks Offers (Today) 🧱✨</h3><p>Cloud Blocks currently ships six production-ready L3 constructs — the same ones our AWS teams use day-to-day. Each comes with sensible defaults and security baked in, so you can move fast without starting from scratch.</p><ul><li><a href="https://leighton-digital.github.io/cloud-blocks/Constructs/api-gateway-cloudfront-distribution/"><strong>API Gateway CloudFront Distribution</strong></a> — Put CloudFront in front of an API Gateway REST stage with HTTPS-only defaults, Route 53 alias, access-log S3 bucket, optional Lambda@Edge, and optional alarms/monitoring.</li><li><a href="https://leighton-digital.github.io/cloud-blocks/Constructs/rest-api/"><strong>Rest Api</strong> </a>— A stage-aware REST API (API Gateway) with default logging, tracing, regional endpoints, secure defaults, and permissive CORS for ephemeral environments.</li><li><a href="https://leighton-digital.github.io/cloud-blocks/Constructs/progressive-lambda/"><strong>Progressive Lambda</strong></a> — A Node.js Lambda with CodeDeploy progressive/canary/linear deployments, CloudWatch alarms, automatic rollback, and X-Ray.</li><li><a href="https://leighton-digital.github.io/cloud-blocks/Constructs/cloudwatch-dashboard/"><strong>CloudWatch Dashboard</strong></a> — A first-class CloudWatch Dashboard (not a wrapper) with an automatic description widget, optional initial widgets, and cdk-nag compliance.</li><li><a href="https://leighton-digital.github.io/cloud-blocks/Constructs/custom-stack/"><strong>Custom Stack</strong></a> — A reusable Stack with optional dashboard integration and a widget registry to keep monitoring organised across the stack lifecycle.</li><li><a href="https://leighton-digital.github.io/cloud-blocks/Constructs/idempotency-table/"><strong>Idempotency Table</strong></a> — A DynamoDB table preconfigured for AWS Lambda Powertools idempotency (id partition key, TTL expiration, encryption on).</li></ul><blockquote><em>Browse the full </em><a href="https://leighton-digital.github.io/cloud-blocks/"><em>construct reference here</em></a><em>.</em></blockquote><h3>Quality gates ✅</h3><p>All constructs come with comprehensive unit tests and cdk-nag checks; we also run CDK synthesis checks to validate what gets created before anything ever ships.</p><h3>What’s next 🔭</h3><p>We’re expanding Cloud Blocks with additional constructs across core infrastructure, networking, observability, data, and AI/ML. If there’s a construct you’d love to see, open an issue or PR!</p><h3>How It’s Structured 🗂️</h3><p>Cloud Blocks is maintained as a poly-repo that publishes a single NPM package, much like how CDK v2 delivers all of its constructs under one distribution. This approach ensures a consistent developer experience — you only need to install and manage one dependency to access the full library of Cloud Blocks constructs.</p><p>To maintain quality and reliability across all constructs, the project includes:</p><ul><li>✅ Unit tests to validate behavior</li><li>🏗️ CDK synthesis checks to confirm constructs synthesise as expected</li><li>🔒 CDK Nag checks to enforce security and compliance best practices</li></ul><p>This setup means every Cloud Block you use is already tested,<strong> </strong>validated, and aligned with AWS best practices, so you can adopt them with confidence.</p><h3>Getting Started 🚀</h3><p>Using Cloud Blocks is straightforward:</p><ol><li>Install the package</li></ol><pre>npm install @leighton-digital/cloud-blocks</pre><p>2. Import a construct into your CDK stack</p><pre>import { Stack, StackProps } from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import * as apigw from &#39;aws-cdk-lib/aws-apigateway&#39;;<br>import * as lambda from &#39;aws-cdk-lib/aws-lambda&#39;;<br>import { RestApi } from &#39;@leighton-digital/cloud-blocks&#39;;<br><br>export class ApiStack extends Stack {<br>  constructor(scope: Construct, id: string, props?: StackProps) {<br>    super(scope, id, props);<br><br>    // Create a stage-aware REST API with sensible defaults<br>    const api = new RestApi(this, &#39;OrdersApi&#39;, {<br>      stageName: &#39;dev&#39;,<br>      description: &#39;Orders service API&#39;,<br>      deploy: true,<br>      isStagingEnvironment: true, // permissive CORS for dev/preview<br>    });<br><br>    // Example Lambdas<br>    const listOrders = new lambda.Function(this, &#39;ListOrdersFn&#39;, {<br>      runtime: lambda.Runtime.NODEJS_22_X,<br>      handler: &#39;index.handler&#39;,<br>      code: lambda.Code.fromInline(&#39;exports.handler=async()=&gt;({statusCode:200,body:&quot;ok&quot;})&#39;)<br>    });<br><br>    const createOrder = new lambda.Function(this, &#39;CreateOrderFn&#39;, {<br>      runtime: lambda.Runtime.NODEJS_22_X,<br>      handler: &#39;index.handler&#39;,<br>      code: lambda.Code.fromInline(&#39;exports.handler=async()=&gt;({statusCode:201,body:&quot;created&quot;})&#39;)<br>    });<br><br>    // Wire resources &amp; methods<br>    const orders = api.api.root.addResource(&#39;orders&#39;);<br>    orders.addMethod(&#39;GET&#39;, new apigw.LambdaIntegration(listOrders));<br>    orders.addMethod(&#39;POST&#39;, new apigw.LambdaIntegration(createOrder));<br>  }<br>}</pre><p>3. Deploy and go!</p><p>You’ll have production-ready resources in minutes, with logging, monitoring, and sensible defaults already configured.</p><h3>How to Contribute 🤝</h3><p>We believe Cloud Blocks will grow stronger with community involvement. Whether you want to:</p><ul><li>Fix a bug 🐞</li><li>Add new constructs 🧩</li><li>Improve docs 📖</li><li>Share feedback 💡</li></ul><p>…we’d love to hear from you.</p><p>Check out the <a href="https://github.com/leighton-digital/cloud-blocks?utm_source=chatgpt.com">Cloud Blocks GitHub repo</a> to get involved. Contributions are welcome from individuals, teams, and organisations that share our vision for simplifying cloud development.</p><h3>Looking Ahead 🔭</h3><p>This is just the beginning. We’re already exploring new constructs for data, AI/ML, and more advanced application patterns. Our goal is to make Cloud Blocks a go-to library for production-ready CDK constructs — and we want you to help shape that journey.</p><h3>Closing Thoughts 🌐</h3><p>Cloud Blocks is our way of giving back to the AWS and CDK community. By sharing the building blocks that help us deliver faster and more securely, we hope to save others from reinventing the wheel — and together, raise the standard for cloud development.</p><p>👉 Check out the <a href="https://github.com/leighton-digital/cloud-blocks">repo</a>, read through the <a href="https://leighton-digital.github.io/cloud-blocks/">documentation</a>, try it out in your next project, and let us know what you think.</p><p>And while you’re at it, don’t miss our other open source projects at <a href="https://tools.leighton.com/">tools.leighton.com</a> — more ways we’re sharing the solutions that power our teams at Leighton.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdc102f5ca8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/on-tech-by-leighton/introducing-cloud-blocks-open-source-reusable-production-grade-cdk-constructs-fdc102f5ca8d">🧱 Introducing Cloud Blocks: Open Source, Reusable, Production-Grade CDK Constructs 🧩</a> was originally published in <a href="https://medium.com/on-tech-by-leighton">on:tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Building Better CDK Stacks: Organise Resources for Faster ⚡ and Safer  Cloud Delivery]]></title>
            <link>https://jcdubs.medium.com/%EF%B8%8F-building-better-cdk-stacks-organise-resources-for-faster-and-safer-cloud-delivery-3ceeb6da60b2?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ceeb6da60b2</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[cloudformation]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Sat, 20 Sep 2025 16:35:45 GMT</pubDate>
            <atom:updated>2025-09-20T16:35:45.430Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical pattern for safer foundations and faster Lambda iterations.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUMd4hfV0YjMZR_Ur-BEJw.png" /></figure><p>When you first start building with the <a href="https://aws.amazon.com/cdk/">AWS Cloud Development Kit (CDK)</a>, it’s tempting to throw all your infrastructure into a single stack and call it a day. It works — until it doesn’t. As your application grows, deployments slow down, risky changes creep in, and the feedback loop between your code and the cloud feels painfully long.</p><p>The truth is: how you organise your CDK stacks has a big impact on how fast, safe, and enjoyable your development process is. In this post, we’ll walk through practical ways to structure your CDK project — beyond the usual <em>stateful vs. stateless</em> split. We’ll look at grouping resources based on how often they change, how risky they are to deploy, and how to keep your iteration cycle as short as possible.</p><p>By the end, you’ll have a set of principles you can apply to your own projects to ship infrastructure changes with more confidence — and less frustration. 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDzdxWlVIPqFsJG9oQIDjA.png" /></figure><h3>What is the AWS CDK?</h3><p>The <a href="https://aws.amazon.com/cdk/">AWS Cloud Development Kit (CDK)</a> is an open-source framework that allows you to define cloud infrastructure using familiar programming languages such as TypeScript, Python, Java, or C#. Instead of hand-crafting long CloudFormation templates, you write infrastructure as code that looks and feels like application code. The CDK then synthesises this code into CloudFormation templates behind the scenes, giving you the reliability and repeatability of CloudFormation with the flexibility of a programming language.</p><h3>Why use the AWS CDK (beyond productivity)</h3><p>The real strength of the CDK comes from what happens after you’ve written that code. It’s not just about productivity — it’s about reusability and recovery.</p><p>By packaging infrastructure patterns into reusable constructs, teams can share consistent building blocks across projects. This reduces duplication and ensures best practices are baked in from the start. Instead of defining a secure S3 bucket or a VPC from scratch every time, you define it once, reuse it everywhere, and avoid the drift that creeps in with manual setups.</p><p>Equally important is recovery. Because your entire environment is defined in code, you’re never dependent on a single fragile console configuration. If a stack is corrupted or accidentally deleted, you can redeploy it from version control and be confident that it will come back exactly as before. This ability to recreate your environment on demand is one of the most valuable aspects of infrastructure as code.</p><p>The CDK still boosts developer productivity by letting you use loops, conditions, and classes to model complex environments more concisely, but its real long-term value is that it makes cloud systems safer, more repeatable, and easier to maintain.</p><h3>CDK in CI/CD pipelines</h3><p>The CDK really comes into its own when paired with continuous delivery. Instead of manually deploying resources, you treat infrastructure changes just like application changes. Your CDK code sits in Git, it’s built and tested in your pipeline, and then deployed automatically into AWS.</p><p>A typical pipeline starts by installing dependencies and synthesising the CDK app into CloudFormation templates. It then deploys those templates into your target environment, whether that’s development, staging, or production. Along the way, you can run integration or smoke tests to make sure everything behaves as expected.</p><p>This process means infrastructure changes go through the same guardrails as code: they’re peer-reviewed, tested, and deployed in a controlled way. The result is safer, more predictable cloud delivery with less room for human error.</p><h3>CDK best practices that matter in production</h3><p>Like any powerful tool, the CDK works best when you follow a set of proven practices. <a href="https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html">AWS provides guidance for how to structure projects and manage resources</a>, and these recommendations often make the difference between a CDK project that scales gracefully and one that becomes difficult to manage over time.</p><p>One of the most important best practices is to separate stateful and stateless resources into different stacks. Stateful resources — like databases, S3 buckets, or Amazon Cognito user pools — tend to hold critical data that shouldn’t be accidentally destroyed or frequently replaced. Stateless resources — like Lambda functions or API Gateway endpoints — are safe to redeploy often. Splitting these into different stacks makes deployments safer and gives you finer control over how changes are rolled out.</p><p>Another best practice is to use construct<strong>s</strong> to encapsulate common patterns. Constructs allow you to model groups of resources as reusable building blocks. This not only reduces duplication but also ensures that security and compliance best practices are applied consistently across environments.</p><p>It’s also recommended to version control your infrastructure right alongside application code. Every change to your CDK app should be committed, reviewed, and traceable. This helps with auditing, rollback, and collaboration across teams.</p><p>Finally, the CDK works best when integrated into automated pipelines. Running cdk synth and cdk deploy manually may work for prototypes, but automated deployments bring consistency and prevent human error from creeping in. Pairing the CDK with CI/CD ensures changes are reviewed, tested, and applied in a repeatable way.</p><p>These best practices form the foundation of effective CDK usage. Once you understand them, you can start to go further — thinking not just about stateful vs. stateless resources, but about how frequency of change, risk level, and developer feedback loops should shape the way you design and organise your stacks.</p><h3>Reference solution we’ll use</h3><p>To make the best practices concrete, let’s walk through a standard solution that many teams build on AWS. This will be the reference architecture we use to explore how to structure CDK projects.</p><p>Imagine we’re building a backend API that will be deployed into a single AWS account as a self-contained environment — whether that’s development, staging, or production. The solution includes the following key pieces:</p><ul><li><strong>API layer:</strong> An Amazon API Gateway serves as the entry point. Behind it sits a set of AWS Lambda functions that implement business logic. This gives us a Serverless, event-driven backend that scales automatically.</li><li><strong>Data layer:</strong> The API is backed by a DynamoDB table. This stateful resource stores our persistent application data and must be protected against accidental replacement.</li><li><strong>Authentication &amp; identity:</strong> We use Amazon Cognito for user management and authentication. To integrate with an existing organisation’s identity system, Cognito is federated with a third-party IdP such as Microsoft Entra ID (formerly Azure AD). This is a sensitive setup that typically changes very rarely.</li><li><strong>Routing &amp; distribution:</strong> Requests flow through Amazon CloudFront, which accelerates delivery and provides caching at the edge. CloudFront sits in front of API Gateway and other assets, providing a single distribution layer.</li><li><strong>Domain name system (DNS):</strong> The public domain is hosted in Route 53. Since many organisations centralise DNS management in a dedicated AWS account, the hosted zone for our application is delegated from the organisation’s central DNS account into the environment account where our API runs.</li></ul><p>This design represents a very typical single-environment serverless web API. It combines fast-moving parts (Lambdas, API routes) with slow-moving and sensitive parts (DynamoDB, Cognito integration, Route 53 delegation). The mix of stateful and stateless resources, combined with both safe-to-redeploy and high-risk resources, makes it the perfect case study for how to structure CDK projects.</p><h3><strong>A baseline CDK layout (stateful vs stateless)</strong></h3><p>Following the CDK best practices we would typically organise these resources in a single CDK project containing a Stateless and Stateful Stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*zN_kqU4iIvb2qPoDwCKsYA.png" /></figure><p>All stateful resources — those that hold or protect data, such as Amazon Cognito and DynamoDB — would live in the Stateful stack, while the Stateless stack would reference and use them. This setup works: the stacks deploy cleanly, the application runs, and everything functions as expected.</p><p>But the real question is what happens next. When the time comes to add new features, will this structure make it easy to maintain and evolve? And when you need to update your Lambda services, can you deploy changes quickly and safely, without putting critical data or configurations at risk?</p><h3>Working in an agile, iterative way</h3><p>The teams I’ve worked with follow a delivery model that emphasises small, frequent changes. Work is broken down into the smallest possible increments, developed in short sprints or iterations, and delivered through pull requests into mature, automated CI/CD pipelines. This steady stream of small updates reduces risk and accelerates feedback.</p><p>A key enabler of this approach is the use of ephemeral environments. In the development account, each pull request spins up a temporary stack as a stage, with the stage name matching the issue or ticket number. This allows multiple developers to work in parallel, each deploying their own isolated environment with dedicated resources.</p><p>Once deployed, the ephemeral environment is validated through unit, integration, and end-to-end tests. Pipeline checks run automatically, and the team reviews the code. If the changes pass review and the pull request is approved, the ephemeral environment is torn down. The change is then merged into the main branch and promoted through staging before finally reaching production.</p><p>While this approach clearly has benefits — enabling developers to work in parallel and deploy changes in isolation — it comes with a significant drawback: the time and cost of deploying the entire stack for every ephemeral environment.</p><p>Take our web API project as an example. For each pull request, a new Route 53 hosted zone, CloudFront distribution, Cognito user pool, API Gateway, and DynamoDB table would be provisioned. This not only adds up to a lengthy deployment process but also drives up costs unnecessarily. Now imagine if the stack also included an RDS cluster. Every ephemeral environment would require spinning up a full database instance, dramatically increasing both deployment time and expense.</p><p>All of this overhead just to validate a small change to one or two Lambda functions makes the process inefficient and unsustainable. But deployment overhead isn’t the only challenge — some components bring their own complexity. Let’s take a closer look.</p><h3>Resources with complex configuration</h3><p>Not all resources are created equal. Some AWS services come with complex configuration steps that are difficult — or sometimes impossible — to fully automate. Two common examples are:</p><ul><li><strong>Route 53 delegation</strong>, where a hosted zone in the application account must be linked back to a parent domain that is managed in a central DNS account or even outside AWS altogether.</li><li><strong>Amazon Cognito federation</strong>, where the user pool in your account has to be integrated with a third-party identity provider such as Microsoft Entra ID (formerly Azure AD).</li></ul><p>In both cases, there are manual elements to the setup. Delegating a subdomain usually involves copying name servers into a registrar’s console or into a central DNS service. Setting up Cognito federation often requires coordination with an identity team to register your application, exchange metadata, and configure secrets or certificates.</p><p>To address this, some organisations build self-service portals or custom CDK/Lambda-backed CloudFormation resources to handle the integration steps. While these solutions help, they don’t remove the fundamental problem: these resources still represent a bottleneck in the release<strong> </strong>process. Any time you create an ephemeral environment or attempt to promote changes, you are blocked until the delegation or identity integration is in place.</p><h3>Understanding risk in infrastructure changes</h3><p>So far, we’ve looked at the challenges of deployment overhead and resource complexity. But there’s another factor that can’t be ignored: <strong>risk</strong>. Not all resources carry the same level of risk when it comes to making changes.</p><p>Some services, like Route 53 delegation or Cognito identity provider integrations, are inherently risky because of their manual or external dependencies. But risk also exists in more “ordinary” resources. For example, with DynamoDB, S3 buckets, or even API Gateway, certain configuration changes can’t be applied in place. Instead, CloudFormation will attempt to <strong>replace</strong> the resource — tearing it down and creating a new one.</p><p>This is where development teams often run into trouble. It’s not always obvious which property updates are destructive. A developer might adjust a setting they think is harmless, only to find that their stack update fails because CloudFormation wants to recreate a critical database or API. In the worst cases, this leads to teams having to manually tear down entire stacks, sometimes in a very specific order, just to get the environment back into a deployable state.</p><p>Not only is this disruptive, it’s also slow and stressful. Valuable time is lost recovering from what was meant to be a small change. For teams trying to work in short iterations with fast feedback loops, this risk can quickly become a major bottleneck.</p><p>The takeaway is that risky resources — whether because of external dependencies or destructive update behaviours — should be treated with extra care.</p><h3>Rethinking layout and deployment strategy</h3><p>By now, we’ve seen how project structure directly impacts the developer experience. Complex configuration introduces manual bottlenecks. Risky resources can be accidentally torn down and force painful redeployments. Lengthy deployments make fast iteration impossible. And ephemeral environments become expensive and slow when every stack recreates the entire world.</p><p>All of these challenges point to the same conclusion: decisions about project layout and deployment strategy really matter. A poor structure slows teams down, increases risk, and undermines the promise of infrastructure as code.</p><p>If we return to our sample project — API Gateway and Lambda, fronted by Route 53 and CloudFront, backed by DynamoDB and Cognito — it’s clear that not all resources are equal. Many of them, such as the hosted zone delegation, CloudFront distribution, DynamoDB table, and Cognito integration, will be created once and rarely touched again. In practice, the only resources that change frequently are the Lambda functions that implement business logic. These are the pieces developers work on every sprint and the ones that drive the need for fast feedback loops.</p><p>A more effective strategy is to separate resources by their risk profile and rate of change. Risky, complex, or slow-moving infrastructure belongs in a Platform project. Fast-changing, low-risk application code belongs in an Application project.</p><ul><li>The Platform project manages foundational infrastructure: Route 53 delegation, CloudFront, API Gateway shell, DynamoDB tables, and Cognito with Entra ID. These stacks are deployed rarely, with care and oversight.</li><li>The Application project focuses on Lambda functions and related stateless glue. These stacks are deployed frequently, often multiple times a day, without the risk of breaking critical infrastructure.</li></ul><p>To connect the two, the Platform project publishes identifiers like ARNs, table names, or user pool IDs as CloudFormation stack exports. The Application project imports these values at deploy time and references the existing resources, without ever owning or recreating them.</p><p>This structure gives us the best of both worlds:</p><ul><li><strong>Safety</strong> by isolating fragile or critical resources.</li><li><strong>Speed</strong> by making Lambda deployments fast and focused.</li><li><strong>Simplicity</strong> by reducing the scope of each stack and clarifying ownership.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdNYyKgQE3m554XhLaQ9Ig.png" /></figure><p>In the next section, we’ll look at how to put this layout into practice, structuring a CDK Platform project and an Application project that work together seamlessly so that deployments are safe, feedback loops are fast, and risky resources are isolated from day-to-day iteration.</p><h3>Putting the layout into practice</h3><p>Now that we’ve outlined why project layout matters, it’s time to put the approach into practice.</p><p>Let’s begin by creating a small utility module that provides reusable functions for exporting and importing values between CloudFormation stacks.</p><pre>// utils.ts<br><br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import config from &#39;./config&#39;;<br>export interface ExportValueProps {<br>    scope: Construct;<br>    value: string;<br>    description: string;<br>    exportName: string;<br>}<br>/**<br> * Export a value to the CDK output<br> * @param scope The scope of the export<br> * @param value The value to export<br> * @param description The description of the export<br> * @param exportName The name of the export<br> */<br>export function exportValue({scope, value, description, exportName} :ExportValueProps): void {<br>    new cdk.CfnOutput(scope, `${exportName}`, {<br>        value,<br>        description,<br>        exportName: `${config.get(&#39;serviceName&#39;)}:${config.get(&#39;envName&#39;)}:${exportName}`,<br>    });<br>}<br>/**<br> * Import a value from the CDK output<br> * @param value <br> * @returns The imported value<br> */<br>export function importValue(value: string): string {<br>  return cdk.Fn.importValue(<br>    `${config.get(&#39;serviceName&#39;)}:${config.get(&#39;envName&#39;)}:${value}`<br>  );<br>}</pre><p>These utilities serve two important purposes:</p><ol><li><strong>Encapsulation</strong> — they abstract away the repetitive logic of working with exports and imports, so teams don’t have to reimplement it in every stack.</li><li><strong>Consistency</strong> — they enforce a clear, predictable naming convention for every exported value, making it easier to reference resources across projects without guesswork.</li></ol><p>By centralising this logic, we reduce duplication, improve readability, and minimise the risk of errors when stacks share information. The utility module is intended to be distributed as a shared npm package, so multiple projects can depend on the same consistent implementation.</p><h4>Platform project: Stateful foundation</h4><p>We create the Platform Stateful stack next — the foundation of our Order Management System. This stack holds the long-lived, high-risk resources that form the backbone of the application and should only be created once.</p><p>In our case, that means a DynamoDB table following a single-table design, an Amazon Cognito user pool (with optional Microsoft Entra ID federation), and a Route 53 hosted zone delegated from the organisation’s central DNS account. These are resources that change rarely, if at all, and carry significant risk if misconfigured or replaced.</p><p>To keep them isolated and safe, we also publish their identifiers as CloudFormation stack exports, so other stacks — like the stateless edge layer or the application stack — can reference them without needing to recreate or modify them. This separation is what enables faster deployments, safer iterations, and smoother collaboration across teams.</p><pre>// platform/lib/stateful.ts<br><br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import * as dynamodb from &#39;aws-cdk-lib/aws-dynamodb&#39;;<br>import * as cognito from &#39;aws-cdk-lib/aws-cognito&#39;;<br>import * as route53 from &#39;aws-cdk-lib/aws-route53&#39;;<br>import { exportValue } from &#39;./utils&#39;;<br>import * as secrets from &#39;aws-cdk-lib/aws-secretsmanager&#39;;<br><br>export interface PlatformStatefulProps extends cdk.StackProps {<br>  envName: string;           // &#39;dev&#39; | &#39;staging&#39; | &#39;prod&#39;<br>  zoneName: string;          // e.g. &#39;orders.example.com&#39;<br>  entra?: {<br>    issuerUrl: string;<br>    clientId: string;<br>    clientSecretValueName: string;<br>    attributeMapping?: cognito.AttributeMapping;<br>  };<br>}<br><br>export class PlatformStatefulStack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props: PlatformStatefulProps) {<br>   super(scope, id, props);<br><br>   const namePrefix = `oms-${props.envName}`;<br><br>   const table = new dynamodb.Table(this, &#39;Table&#39;, {<br>      tableName: `${namePrefix}-main`,<br>      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,<br>      partitionKey: { name: &#39;PK&#39;, type: dynamodb.AttributeType.STRING },<br>      sortKey: { name: &#39;SK&#39;, type: dynamodb.AttributeType.STRING },<br>      pointInTimeRecovery: true,<br>      timeToLiveAttribute: &#39;TTL&#39;, <br>      stream: dynamodb.StreamViewType.NEW_AND_OLD_IMAGES,<br>      removalPolicy: cdk.RemovalPolicy.RETAIN,<br>    });<br><br>    // -------------------------- Cognito (IdP-ready) --------------------------<br>    const userPool = new cognito.UserPool(this, &#39;UserPool&#39;, {<br>      userPoolName: `${namePrefix}-users`,<br>      selfSignUpEnabled: false,<br>      signInAliases: { email: true },<br>      accountRecovery: cognito.AccountRecovery.EMAIL_ONLY,<br>      removalPolicy: cdk.RemovalPolicy.RETAIN,<br>    });<br><br>    const userPoolDomain = new cognito.UserPoolDomain(this, &#39;UserPoolDomain&#39;, {<br>      userPool,<br>      cognitoDomain: { domainPrefix: `${namePrefix}-auth` },<br>    });<br><br>    const userPoolClient = new cognito.UserPoolClient(this, &#39;UserPoolClient&#39;, {<br>      userPool,<br>      userPoolClientName: `${namePrefix}-app-client`,<br>      generateSecret: false,<br>      oAuth: {<br>        flows: { authorizationCodeGrant: true },<br>        scopes: [cognito.OAuthScope.OPENID, cognito.OAuthScope.EMAIL, cognito.OAuthScope.PROFILE],<br>        // Replace once CloudFront domain exists:<br>        callbackUrls: [&#39;https://placeholder.example/callback&#39;],<br>        logoutUrls: [&#39;https://placeholder.example/logout&#39;],<br>      },<br>      preventUserExistenceErrors: true,<br>    });<br><br>    if (props.entra) {<br><br>      const entraSecret = props.entra<br>        ? secrets.Secret.fromSecretNameV2(this, &#39;EntraClientSecret&#39;, props.entra.clientSecretValueName)<br>        : undefined;<br><br>      new cognito.UserPoolIdentityProviderOidc(this, &#39;EntraProvider&#39;, {<br>        userPool,<br>        name: &#39;EntraID&#39;,<br>        issuerUrl: props.entra.issuerUrl,<br>        clientId: props.entra.clientId,<br>        clientSecret: entraSecret ? entraSecret.secretValue : cdk.SecretValue.unsafePlainText(&#39;REPLACE_ME&#39;),<br>        attributeRequestMethod: cognito.OidcAttributeRequestMethod.POST,<br>        attributeMapping: props.entra.attributeMapping ?? {<br>          email: cognito.ProviderAttribute.other(&#39;email&#39;),<br>          givenName: cognito.ProviderAttribute.other(&#39;given_name&#39;),<br>          familyName: cognito.ProviderAttribute.other(&#39;family_name&#39;),<br>        },<br>        scopes: [&#39;openid&#39;, &#39;email&#39;, &#39;profile&#39;],<br>      });<br>    }<br><br>    // ----------------------- Route 53 (delegated zone) -----------------------<br>    const hostedZone = new route53.PublicHostedZone(this, &#39;HostedZone&#39;, {<br>      zoneName: props.zoneName,<br>    });<br><br>    // ------------------------------ Outputs ----------------------------------<br>    exportValue({<br>      scope: this,<br>      value: hostedZone.hostedZoneNameServers?.join(&#39;,&#39;) ?? &#39;create zone first&#39;,<br>      description: &#39;Provide these NS records to the central DNS team for delegation&#39;,<br>      exportName: &#39;ZoneNameServers&#39;,<br>    });<br>    exportValue({<br>      scope: this,<br>      value: table.tableName,<br>      description: &#39;The name of the Orders table&#39;,<br>      exportName: &#39;OrdersTableName&#39;,<br>    });<br>    exportValue({<br>      scope: this,<br>      value: table.tableStreamArn ?? &#39;&#39;,<br>      description: &#39;The ARN of the Orders table stream&#39;,<br>      exportName: &#39;OrdersTableStreamArn&#39;,<br>    });<br>    exportValue({<br>      scope: this,<br>      value: userPool.userPoolId,<br>      description: &#39;The ID of the Orders User Pool&#39;,<br>      exportName: &#39;UserPoolId&#39;,<br>    });<br>    exportValue({<br>      scope: this,<br>      value: userPoolClient.userPoolClientId,<br>      description: &#39;The ID of the Orders User Pool Client ID&#39;,<br>      exportName: &#39;UserPoolClientId&#39;,<br>    });<br>    exportValue({<br>      scope: this,<br>      value: userPoolDomain.domainName,<br>      description: &#39;The domain name of the Orders User Pool&#39;,<br>      exportName: &#39;UserPoolDomainName&#39;,<br>    });<br>    exportValue({<br>      scope: this,<br>      value: hostedZone.hostedZoneId,<br>      description: &#39;The ID of the Hosted Zone&#39;,<br>      exportName: &#39;HostedZoneID&#39;,<br>    });<br>    exportValue({<br>      scope: this,<br>      value: hostedZone.zoneName,<br>      description: &#39;The name of the Hosted Zone&#39;,<br>      exportName: &#39;ZoneName&#39;,<br>    });<br>  }<br>}</pre><h4>Platform project: Stateless edge</h4><p>With the stateful foundation in place, the next piece is the Platform Stateless stack. This stack contains resources that don’t directly hold data, but are central to how traffic flows into the system.</p><p>For our Order Management System, this means:</p><ul><li><strong>Amazon API Gateway</strong>, which defines the API shell and entry point for requests. The routes and methods here change less frequently than the Lambda code behind them.</li><li><strong>Amazon CloudFront</strong>, which sits in front of API Gateway to provide caching, security, and global performance.</li><li><strong>Integration with Route 53</strong>, which will later point the delegated subdomain (created in the stateful stack) to the CloudFront distribution.</li></ul><pre>// platform/lib/stateless.ts<br><br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import * as apigw from &#39;aws-cdk-lib/aws-apigateway&#39;;<br>import * as cloudfront from &#39;aws-cdk-lib/aws-cloudfront&#39;;<br>import * as origins from &#39;aws-cdk-lib/aws-cloudfront-origins&#39;;<br>import * as route53 from &#39;aws-cdk-lib/aws-route53&#39;;<br>import * as targets from &#39;aws-cdk-lib/aws-route53-targets&#39;;<br>import { exportValue } from &#39;./utils&#39;;<br><br>export interface PlatformStatelessProps extends cdk.StackProps {<br>  envName: string;     // e.g. &#39;dev&#39; | &#39;staging&#39; | &#39;prod&#39;<br>  zoneName: string;    // e.g. &#39;orders.example.com&#39;<br>}<br><br>export class PlatformStatelessStack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props: PlatformStatelessProps) {<br>    super(scope, id, props);<br><br>    const namePrefix = `oms-${props.envName}`;<br><br>    // ------------------------ API Gateway (shell) ----------------------------<br>    const api = new apigw.RestApi(this, &#39;Api&#39;, {<br>      restApiName: `${namePrefix}-api`,<br>      // We dont deploy the API - We do this in the Application stack.<br>      deploy: false,<br>      defaultCorsPreflightOptions: {<br>        allowOrigins: apigw.Cors.ALL_ORIGINS,<br>        allowMethods: [&#39;GET&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;DELETE&#39;, &#39;OPTIONS&#39;],<br>      },<br>    });<br><br>    // ---------------- Health Check Resource ----------------------------<br><br>    // We add a health check resource to the API because CloudFormation<br>    // doesn&#39;t allow the API to not have a method regardless of whether<br>    // the API Gateway distribution is being deployed or not.<br>    const health = api.root.addResource(&#39;_health&#39;);<br><br>    health.addMethod(<br>      &#39;GET&#39;,<br>      new apigw.MockIntegration({<br>        passthroughBehavior: apigw.PassthroughBehavior.NEVER,<br>        requestTemplates: { &#39;application/json&#39;: &#39;{&quot;statusCode&quot;: 200}&#39; },<br>        integrationResponses: [{<br>          statusCode: &#39;200&#39;,<br>          responseTemplates: { &#39;application/json&#39;: &#39;{&quot;ok&quot;: true}&#39; },<br>        }],<br>      }),<br>      {<br>        methodResponses: [{ statusCode: &#39;200&#39; }],<br>      }<br>    );<br><br>    // -------------------------- CloudFront distro ----------------------------<br>    const distribution = new cloudfront.Distribution(this, &#39;Distro&#39;, {<br>      defaultBehavior: {<br>        origin: new origins.RestApiOrigin(api),<br>        viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,<br>      },<br>    });<br><br>    // ----------------------- Route 53 alias record ---------------------------<br>    const hostedZone = route53.HostedZone.fromLookup(this, &#39;HostedZone&#39;, {<br>      domainName: props.zoneName,<br>    });<br><br>    new route53.ARecord(this, &#39;AliasRecord&#39;, {<br>      zone: hostedZone,<br>      recordName: &#39;api&#39;, // e.g. api.orders.example.com<br>      target: route53.RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution)),<br>    });<br><br>    // ------------------------------- Outputs ---------------------------------<br>    <br>    exportValue({<br>      scope: this,<br>      value: api.restApiId,<br>      description: &#39;The Rest API ID&#39;,<br>      exportName: &#39;OrdersRestApiId&#39;,<br>    });<br><br>    exportValue({<br>      scope: this,<br>      value: api.root.resourceId,<br>      description: &#39;The ID of the Orders API root resource&#39;,<br>      exportName: &#39;OrdersApiRootResourceId&#39;,<br>    });    <br><br>    exportValue({<br>      scope: this,<br>      value: distribution.distributionId,<br>      description: &#39;The ID of the CloudFront distribution&#39;,<br>      exportName: &#39;CloudFrontDistributionId&#39;,<br>    });<br><br>    exportValue({<br>      scope: this,<br>      value: distribution.distributionDomainName,<br>      description: &#39;The name of the CloudFront distribution&#39;,<br>      exportName: &#39;CloudFrontDistributionName&#39;,<br>    });<br>  }<br>}</pre><p>This platform stateless stack gives us a stable API entry point and global distribution layer that we rarely need to touch. The Application stack can then wire its Lambdas to the API resources and publish branch-based stages without ever owning CloudFront or API Gateway itself.</p><p>We next create instances of the <em>PlatformStatefulStack</em> and <em>PlatformStatelessStack</em> ensuring that the name of both stacks contain the environment name.</p><pre>// platform/bin/platform.ts<br><br>#!/usr/bin/env node<br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { PlatformStatefulStack, PlatformStatelessStack } from &#39;../lib&#39;;<br>import config from &#39;../lib/config&#39;;<br>const stackConfig = {<br>  serviceName: config.get(&#39;serviceName&#39;),<br>  envName: config.get(&#39;envName&#39;),<br>};<br>const app = new cdk.App();<br>new PlatformStatefulStack(app, `PlatformStatefulStack-${config.get(&#39;envName&#39;)}`, stackConfig);<br>new PlatformStatelessStack(app, `PlatformStatelessStack-${config.get(&#39;envName&#39;)}`, stackConfig);</pre><h4>Application project: Stateless services</h4><p>With the Platform stacks in place, we can now turn our attention to the Application Stateless stack. In the case of the Orders application, there’s no need for an Application Stateful stack — this project doesn’t own any long-lived resources such as databases or identity stores.</p><p>Instead, the focus of the Application project is on the fast-moving parts of the system: defining the Orders API resources and methods, deploying the Lambda functions that implement business logic, and managing the API Gateway deployments that expose those endpoints. This separation keeps the application code lightweight and easy to iterate on, while still plugging cleanly into the foundational infrastructure provided by the Platform stacks.</p><pre>// application/lib/stateless.ts<br><br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import * as lambda from &#39;aws-cdk-lib/aws-lambda&#39;;<br>import * as nodeLambda from &#39;aws-cdk-lib/aws-lambda-nodejs&#39;;<br>import path from &#39;node:path&#39;;<br>import * as apigateway from &#39;aws-cdk-lib/aws-apigateway&#39;;<br>import * as dynamodb from &#39;aws-cdk-lib/aws-dynamodb&#39;;<br>import * as cognito from &#39;aws-cdk-lib/aws-cognito&#39;;<br>import { importValue, exportValue } from &#39;./utils&#39;;<br>import { EnvName } from &#39;./types&#39;;<br><br>// Define default Lambda environment variables.<br>const defaultEnvironment = {<br>  LOG_LEVEL: &#39;DEBUG&#39;,<br>  POWERTOOLS_LOGGER_LOG_EVENT: &quot;true&quot;,<br>  POWERTOOLS_LOGGER_SAMPLE_RATE: &quot;1&quot;,<br>  POWERTOOLS_TRACE_ENABLED: &quot;enabled&quot;,<br>  POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS: &quot;captureHTTPsRequests&quot;,<br>  POWERTOOLS_TRACER_CAPTURE_RESPONSE: &quot;captureResult&quot;,<br>};<br><br>// Define the common lambda properties used by all Lambda services.<br>const commonLambdaProps = {<br>  runtime: lambda.Runtime.NODEJS_20_X,<br>  architecture: lambda.Architecture.ARM_64,<br>  handler: &#39;handler&#39;,<br>  awsSdkConnectionReuse: true,<br>  tracing: lambda.Tracing.ACTIVE,<br>  timeout: cdk.Duration.seconds(15),<br>  bundling: {<br>    minify: true,<br>    sourceMap: true,<br>    sourceMapMode: nodeLambda.SourceMapMode.INLINE,<br>    sourcesContent: false,<br>    target: &quot;node20&quot;,<br>    externalModules: [&quot;@aws-sdk/*&quot;],<br>  },<br>}<br><br>/**<br> * ApplicartionStack props providing the service name, environment name<br> * and deployment stage name.<br> */<br>interface ApplicationStackProps extends cdk.StackProps {<br>  serviceName: string;<br>  envName: EnvName;<br>  stageName: string;<br>}<br><br>/**<br> * Orders Application Stateless stack.<br> */<br>export class ApplicationStatelessStack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props: ApplicationStackProps) {<br>    super(scope, id, props);<br><br>    // ------- Import values exported by the Platform stacks-----------------<br><br>    const ordersTableName = importValue(&#39;OrdersTableName&#39;);<br>    const ordersRestApiId = importValue(&#39;OrdersRestApiId&#39;);<br>    const ordersApiResourceId = importValue(&#39;OrdersApiRootResourceId&#39;);<br>    const userPoolId = importValue(&#39;UserPoolId&#39;);<br><br>    // ------- Create Orders Lambda functions -----------------<br><br>    const createOrderFunction = new nodeLambda.NodejsFunction(this, &#39;CreateOrderLambda&#39;, {<br>      ...commonLambdaProps,<br>      entry: path.join(<br>        __dirname,<br>        &quot;../src/handler/create-order-function/index.ts&quot;<br>      ),<br>      description: &quot;Create an Order&quot;,<br>      environment: {<br>        ...defaultEnvironment,<br>        ORDERS_TABLE: ordersTableName,<br>        STAGE_NAME: props.stageName<br>      }<br>    });<br><br>    const getOrderFunction = new nodeLambda.NodejsFunction(this, &#39;GetOrderLambda&#39;, {<br>      ...commonLambdaProps,<br>      entry: path.join(<br>        __dirname,<br>        &quot;../src/handler/get-order-function/index.ts&quot;<br>      ),<br>      description: &quot;Get an order by id&quot;,<br>      environment: {<br>        ...defaultEnvironment,<br>        ORDERS_TABLE: ordersTableName,<br>        STAGE_NAME: props.stageName<br>      }<br>    });<br><br>    // ------- Reference Orders table and create permissions -----------------<br><br>    const ordersTable = dynamodb.Table.fromTableName(this, &#39;OrdersTable&#39;, ordersTableName);<br>    ordersTable.grantReadWriteData(createOrderFunction);<br>    ordersTable.grantReadData(getOrderFunction);<br><br>    // ------- Reference Orders API -----------------<br><br>    const ordersApi = apigateway.RestApi.fromRestApiAttributes(this, &#39;OrdersApi&#39;, {<br>      restApiId: ordersRestApiId,<br>      rootResourceId: ordersApiResourceId,<br>    });<br><br>    // ------- Create Orders API resources -----------------<br><br>    const ordersVersionResource = ordersApi.root.addResource(props.stageName !== props.envName ? props.stageName : &#39;v1&#39;);<br>    const ordersApiResource = ordersVersionResource.addResource(&#39;orders&#39;);<br>    const orderByIdResource = ordersApiResource.addResource(&#39;{orderId}&#39;);<br><br>    // ------- Reference Orders User pool -----------------<br><br>    // Reference the Cognito User Pool<br>    const userPool = cognito.UserPool.fromUserPoolId(<br>      this,<br>      &#39;UserPool&#39;,<br>      userPoolId<br>    );<br><br>    // ------- Create Cognito Authorizer -----------------<br>    <br>    const cognitoAuthorizer = new apigateway.CognitoUserPoolsAuthorizer(<br>      this,<br>      &#39;CognitoAuthorizer&#39;,<br>      {<br>        cognitoUserPools: [userPool],<br>        authorizerName: `${props.serviceName}-cognito-authorizer-${props.stageName}`,<br>        identitySource: &#39;method.request.header.Authorization&#39;,<br>      }<br>    );<br><br>    const methodProps = {<br>      authorizer: cognitoAuthorizer,<br>      authorizationType: apigateway.AuthorizationType.COGNITO,<br>    };<br><br>    // ------- Create Orders CRUD methods -----------------<br><br>    ordersApiResource.addMethod(&#39;POST&#39;, new apigateway.LambdaIntegration(createOrderFunction), methodProps);<br>    orderByIdResource.addMethod(&#39;GET&#39;, new apigateway.LambdaIntegration(getOrderFunction), methodProps);<br><br>    // ------- Create Orders API Deployment -----------------<br><br>    const deployment = new apigateway.Deployment(this, `Deployment`, { api:ordersApi });<br>    deployment.node.addDependency(ordersApiResource, orderByIdResource);<br><br>    // ------- Create Orders API Stage -----------------<br><br>    new apigateway.Stage(this, `Stage-${props.stageName}`, {<br>      stageName: props.stageName,<br>      deployment,<br>      loggingLevel: apigateway.MethodLoggingLevel.INFO,<br>      metricsEnabled: true,<br>    });<br><br>    // ------- Exports -----------------<br><br>    exportValue({<br>      scope: this,<br>      value: `https://${ordersApi.restApiId}.execute-api.${cdk.Aws.REGION}.amazonaws.com/${props.stageName}`,<br>      description: &#39;The Order API invoke URL&#39;,<br>      exportName: &#39;OrdersApiURL&#39;,<br>    });<br>  }<br>}</pre><p>With the Platform stacks in place, the Application Stateless stack steps in to handle the fast-moving parts of the Orders service. Rather than creating any long-lived resources, it imports what it needs from the Platform layer: the DynamoDB table, the existing API Gateway, and the Cognito User Pool. This keeps the application layer lightweight and focused on code and endpoints.</p><p>To keep things consistent, the stack defines a set of default Lambda properties and common environment variables. That way, every function deployed into this project shares the same runtime, tracing, logging, and build settings. From there, the Orders application defines two Lambdas: one to create orders and another to retrieve them by ID. Each function receives the DynamoDB table name and stage name as environment variables and is granted only the level of access it requires.</p><p>Once the Lambdas are in place, the stack attaches them to the imported API. It extends the API by adding a stage-specific versioned path (either a branch name for a preview environment or v1 for stable environments) and creates /orders and /orders/{orderId} resources beneath it. The Cognito User Pool from the Platform stack is then used to set up an authorizer, ensuring that all requests to these methods are properly authenticated.</p><p>Finally, the stack deploys the API changes into a new stage that matches the branch or ticket name. This makes it easy for developers to spin up ephemeral environments during pull requests and test their changes in isolation. Each deployment exports its own invoke URL, so the resulting endpoint can be linked directly from the CI/CD pipeline or PR checks.</p><p>The end result is a structure that’s fast to deploy, safe to iterate on, and consistent across environments: Platform stacks own the risky, slow-moving pieces, while the Application stack focuses on the day-to-day business logic and the routes that expose it.</p><p>We finally implement the ApplicationStatelessStack in the entry point script of the Application project.</p><pre>// application/bin/application<br><br>#!/usr/bin/env node<br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { ApplicationStatelessStack } from &#39;../lib/application-stack&#39;;<br>import config from &#39;../lib/config&#39;;<br><br>const stage = config.get(&#39;stage&#39;) ?? config.get(&#39;envName&#39;);<br><br>const app = new cdk.App();<br>new ApplicationStatelessStack(app, `ApplicationStatelessStack-${stage}`, {<br>  serviceName: config.get(&#39;serviceName&#39;),<br>  envName: config.get(&#39;envName&#39;),<br>  stageName: stage,<br>});</pre><p>The entrypoint script determines the stack name dynamically from environment variables. If a STAGE value is provided, it takes precedence; otherwise the stack name falls back to the ENV_NAME. This stage value is included in the name of the Application Stateless stack, ensuring that every deployment has a clear and predictable identity.</p><p>For example, deploying with ENV_NAME=dev produces or updates a stack named ApplicationStatelessStack-dev, while deploying with ENV_NAME=dev and STAGE=cb-1 creates or updates a separate stack named ApplicationStatelessStack-cb-1. This convention gives developers the ability to spin up isolated, ephemeral environments for feature branches or pull requests, while operators benefit from the predictability of uniquely named stacks.</p><p>Each of these stacks manages its own API Gateway stage, endpoints, and Lambda functions, so multiple developers can work in parallel without colliding with one another’s deployments. Reviewers gain the ability to test changes in fully functional cloud environments, and once a pull request is approved and merged, the corresponding ephemeral stack can be torn down. That cleanup step not only reclaims resources and reduces cost, but also simplifies operations by ensuring the environment stays clean and free of unused infrastructure.</p><h3>Environments and deployments</h3><p>The image below demonstrates how the platform and application stacks are deployed to each environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mW53feZi_xxfSYq9oD7vvw.png" /></figure><p>The screenshot below shows what the deployed API Gateway looks like once both the <strong>dev</strong> stage and an ephemeral <strong>cb-1</strong> stage have been created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*67YdOqT4DGwR62XWoKTjeA.png" /></figure><p>Each stage maintains its own resource tree and methods, meaning that multiple environments can coexist on the same API without interfering with each other. The <strong>dev</strong> stage contains the stable /v1/orders resource, with POST for creating orders and GET /{orderId} for retrieving them. This is the baseline development environment that the team works against day to day.</p><p>Alongside it, the cb-1 stage has been created from a feature branch. It mirrors the same /v1/orders resources and methods but is isolated under its own stage path (/cb-1/orders). This allows developers to deploy their branch-specific Lambda code without affecting the shared development or staging stacks. Reviewers can test these changes directly against the cb-1 stage endpoint, giving fast feedback on pull requests.</p><p>When the feature branch is merged, the cb-1 stage can be safely torn down, removing its endpoints and Lambdas while leaving the dev stage intact. This illustrates the power of ephemeral environments in practice: parallel development with no collisions, quick feedback, and automatic cleanup when no longer needed.</p><p>Another advantage of this approach is how straightforward it makes end-to-end testing in the CI pipeline. The API Gateway distribution URL remains the same across all stages; what changes is simply the path prefix. For stable environments, requests are routed through the versioned root resource — for example, /v1/orders. For ephemeral environments created from feature branches, the root resource matches the stage name—for example, /cb-1/orders.</p><p>This means test suites don’t need to be rewritten or reconfigured for every environment. Instead, the CI pipeline can substitute the correct stage name or version prefix into the request paths. End-to-end tests can then be run automatically against the dev, staging, or ephemeral feature environments using the same API Gateway distribution, providing reliable feedback with minimal setup.</p><p>By aligning deployment stages with branch names and using a consistent distribution URL, the system simplifies both developer workflows and automated testing. Teams can verify that new code behaves as expected in an isolated environment, confident that tests are targeting the exact version of the API under review.</p><h4>Quotas &amp; cleanup</h4><p>One thing to keep in mind when using ephemeral stages is that Amazon API Gateway has quotas on the number of stages and deployments per API. If every pull request creates a new stage and you don’t tear it down, you can hit those limits quickly.</p><p>To avoid running into quotas (and unnecessary costs), make sure that PR stacks and their API stages are automatically destroyed once the branch is merged or closed.</p><p>It’s also a good practice to set short log retention for these ephemeral environments. That way, you still get logs for debugging during review, but avoid building up a long trail of unused CloudWatch data after the environment is gone.</p><h3>Considerations (not one-size-fits-all)</h3><p>While this pattern of separating platform and application stacks with ephemeral environments brings clear benefits, it isn’t a one-size-fits-all solution. Like any architecture, it will require adjustments depending on your use case, your team’s practices, and especially your data layer.</p><p>One challenge arises when feature work introduces changes to the data model. If two stages share the same underlying database, a breaking change in one branch may cause backward compatibility issues for other environments that don’t yet include the change. This can limit the usefulness of parallel ephemeral deployments unless the data strategy is adapted.</p><p>The way forward depends heavily on the technology in play. With a relational database, for example, a developer might decide to create new tables that reflect the updated schema and scope those only to the feature stage. In this setup, migration and hydration scripts would be executed against the temporary tables while the canonical schema remains unchanged. Once the feature is merged, the same scripts can be applied to the production database.</p><p>If DynamoDB is the chosen store, the problem might be approached differently. DynamoDB’s flexible schema allows teams to handle data model evolution at the application layer instead of the data layer. The application code can be written to support both old and new item structures during the transition period, reducing the risk of breaking other active stages.</p><p>In practice, no single approach works universally. The right choice depends on the nature of your data, the tolerance for breaking changes, and the complexity your team is willing to manage. The pattern described here provides a solid foundation, but it should always be adapted to fit the specific needs of your system and your organisation.</p><h3>Wrapping Up</h3><p>We’ve walked through why the way you structure your CDK projects matters, the pitfalls of lumping everything together, and how splitting resources into Platform and Application stacks unlocks safer, faster, and more flexible cloud delivery.</p><p>By isolating long-lived, risky resources (like Cognito, DynamoDB, Route 53, and CloudFront) in Platform stacks and keeping fast-moving Lambda functions and API methods in Application stacks, you get the best of both worlds:</p><ul><li><strong>Safety</strong>: foundational infrastructure is protected from accidental redeployments.</li><li><strong>Speed</strong>: Lambda code can be iterated on quickly with minimal deployment overhead.</li><li><strong>Flexibility</strong>: ephemeral environments enable parallel development and clean tear-downs.</li></ul><p>This pattern isn’t a silver bullet — real projects will always have unique challenges around data models, risk tolerance, or integration with external systems. But it provides a solid starting point for teams that want to improve feedback loops, reduce risk, and bring order to their CDK projects.</p><p>Thanks for taking the time to read this deep dive 🙏. I hope it helps you think differently about how to structure your stacks and makes your cloud delivery just a little bit faster ⚡ and safer 🔒.</p><p>If you have questions, ideas, or experiences of your own, I’d love to hear them — drop a comment or reach out. Happy building! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ceeb6da60b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CDK & DynamoDB GSIs ⚡— Beating the One-Index-Per-Update Bottleneck ]]></title>
            <link>https://jcdubs.medium.com/aws-cdk-dynamodb-gsis-beating-the-one-index-per-update-bottleneck-7ec5d08ddd3a?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ec5d08ddd3a</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[amazon-dynamodb]]></category>
            <category><![CDATA[single-table-design]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 08:31:22 GMT</pubDate>
            <atom:updated>2025-08-14T08:31:22.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcJ7OXtyiGdtBfLJXp1E7Q.png" /></figure><p>When working with AWS DynamoDB through the AWS CDK, adding a new Global Secondary Index (GSI) feels like it should be a simple update — define it in your stack, deploy, and you’re done. But there’s a catch: CloudFormation only allows one GSI to be added or deleted per stack update.</p><p>This limitation often goes unnoticed until it slows down your workflow. You might be iterating on your schema, adding multiple indexes for new access patterns, or cleaning up unused ones — only to discover that each change now requires a separate deployment cycle. In larger environments, that can mean multiple Pull Requests (PRs), longer release times, and extra operational overhead and even worse problems when trying to recover from failure.</p><p>In this post, we’ll break down:</p><ul><li>Why this one-GSI-per-update limit exists in CloudFormation</li><li>How it impacts CDK-based DynamoDB table management in real projects</li><li>A practical strategy to create and manage GSIs in a way that keeps your deployments smooth and your data intact</li></ul><p>By the end, you’ll be able to plan your DynamoDB schema changes without hitting the dreaded “Update limit exceeded” roadblock. 🚀</p><h3>Understanding Global Secondary Indexes (GSIs) in DynamoDB</h3><p>Before we talk about the one-GSI-per-update rule, it’s worth touching on what a Global Secondary Index (GSI) actually is — and why it’s a core tool in DynamoDB schema design.</p><h4>1. What is a GSI?</h4><p>A Global Secondary Index is a data structure that lets you query your DynamoDB table using an alternate partition key and sort key combination from your base table.</p><ul><li>Unlike a Local Secondary Index (LSI), which shares the same partition key as the base table, a GSI can have a completely different partition key.</li><li>This makes GSIs ideal for supporting multiple query patterns without duplicating data in separate tables.</li></ul><p>When you create a GSI, DynamoDB maintains it automatically — any writes to your base table are also written to the index if the indexed attributes are present.</p><h4>2. Why GSIs are crucial for Single Table Design.</h4><p>In <a href="https://aws.amazon.com/blogs/compute/creating-a-single-table-design-with-amazon-dynamodb/">Single Table Design (STD)</a>, you store all entity types in one table and model different access patterns through partition key and sort key combinations.</p><ul><li>A single table might hold Users, Orders, Products, and Shipments — all with different key structures.</li><li>Your base table’s primary key supports your main access pattern (e.g., look up all orders for a user).</li><li>GSIs give you secondary access patterns (e.g., look up all orders by status, find shipments by carrier, or list products by category).</li></ul><p>Without GSIs, you’d have to either:</p><ol><li>Perform inefficient table scans, or</li><li>Create multiple tables — losing the benefits of STD like simpler transactions and reduced operational overhead.</li></ol><h4>3. How GSIs enable query flexibility.</h4><p>Some example GSI uses in Single Table Design:</p><ul><li><strong>GSI1</strong>: PK = OrderStatus, SK = OrderDate → List orders by status and sort by date.</li><li><strong>GSI2</strong>: PK = ProductCategory, SK = Price → Query products by category with price sorting.</li><li><strong>GSI3</strong>: PK = CustomerEmail, SK = LastLogin → Look up customers by email address.</li></ul><p>Each GSI gives you a new “lens” on your data, unlocking queries that would otherwise be impossible or inefficient.</p><p>By understanding how GSIs underpin Single Table Design, the one-GSI-per-update limit in CloudFormation becomes more than just a technical quirk — it’s a constraint that can directly slow down your ability to evolve your data model.</p><h3>Why the One-GSI-Per-Update Limit Exists in CloudFormation.</h3><p>If you’ve ever tried to add two GSIs in a single AWS CDK deployment, you’ve probably run into the dreaded CloudFormation error telling you that you can only make one GSI change per update. This isn’t an arbitrary CDK rule — it’s rooted in how DynamoDB itself handles index operations.</p><h4><strong>1. DynamoDB can only build or delete one index at a time.</strong></h4><p>When you create a Global Secondary Index on an existing table, DynamoDB must scan every item in the table to populate the new index with the required attributes — a process called backfilling.</p><ul><li>Backfill is resource-intensive and can take from minutes to hours, depending on the size of your table and provisioned throughput.</li><li>To protect table performance and avoid overloading storage, DynamoDB enforces a one-index-at-a-time rule for both creation and deletion.</li></ul><h4>2. CloudFormation maps directly to DynamoDB’s API restrictions.</h4><p>When CloudFormation updates a table resource, it calls the DynamoDB UpdateTable API. That API:</p><ul><li>Allows one GSI to be created per call.</li><li>Allows one GSI to be deleted per call.</li><li>Does not allow both in a single request.</li></ul><p>Since CloudFormation treats resource updates as a single atomic operation, it can’t automatically split multiple GSI changes into multiple sequential UpdateTable calls. The limitation is therefore surfaced directly in CloudFormation.</p><h4>3. It’s also about operational safety.</h4><p>AWS keeps this restriction in place for safety reasons:</p><ul><li>Prevents long-running, overlapping index builds that could impact read/write latency.</li><li>Reduces the risk of partially applied schema changes.</li><li>Keeps rollback paths simpler if something fails during a deployment.</li></ul><p>This limit is a DynamoDB service-level rule, not just a CloudFormation quirk. The CDK simply inherits it when it synthesises to CloudFormation.</p><h3>How the One-GSI-Per-Update Limit Impacts CDK-Based DynamoDB Management.</h3><p>When you’re using the <strong>AWS Cloud Development Kit (CDK)</strong> to manage your infrastructure, your DynamoDB table definition lives as code. That’s great for consistency, but it also means every schema change goes through CloudFormation — and therefore inherits DynamoDB’s one-GSI-per-update rule.</p><h4>1. Slower schema evolution</h4><p>If you discover you need multiple new indexes to support a feature, you can’t just add them all to your CDK construct and deploy once. Instead, you need:</p><ul><li>One deployment per index addition (waiting for backfill each time).</li><li>The same restriction for index deletions.</li><li>No ability to create and delete indexes in the same deployment.</li></ul><p>For a large table with millions of items, each backfill might take hours — turning what you thought was a “quick update” into a multi-day rollout.</p><h4>2. More complex PR and release cycles</h4><p>In a team setting:</p><ul><li>A pull request adding two new GSIs will fail deployment.</li><li>You might need to split changes into multiple PRs, which increases review overhead.</li><li>Feature branches may need to be rebased after each deployment, to keep infrastructure state in sync.</li></ul><p>This can cause friction for developers, especially in fast-moving projects where features and access patterns are evolving quickly.</p><h4>3. Higher operational risk during feature launches</h4><p>If a new feature requires multiple access patterns, you might have to stage the rollout — deploy GSI #1, wait for it to become ACTIVE, then deploy GSI #2. This can introduce awkward “in-between” states where the application or API needs to handle partially available features.</p><h4>4. Limited refactoring flexibility</h4><p>If you’re rethinking your Single Table Design, you can’t replace multiple GSIs in a single CDK update. This slows down large-scale schema refactors, especially in early stages when query patterns aren’t fully settled.</p><p>In real-world CDK projects, the one-GSI-per-update limit isn’t just a minor technical detail — it shapes how you design, plan, and deploy schema changes.</p><p>Lets say we define our DynamoDB table in a StatefulCDK stack like so:</p><pre>...<br><br>export class StatefulStack extends Stack {<br>  readonly customerTable: dynamodb.Table;<br><br>  constructor(<br>      scope: Construct,<br>      id: string,<br>      readonly props: StackProps,<br>    ) {<br>      super(scope, id, props);<br><br>      // Create the Customer table<br>      this.customerTable = new dynamodb.Table(<br>        this,<br>        `CustomerTable-${props.stage}`,<br>        {<br>          tableName: `${props.stage}-customer-table`,<br>          partitionKey: {name: &#39;PK&#39;, type: dynamodb.AttributeType.STRING},<br>          sortKey: {name: &#39;SK&#39;, type: dynamodb.AttributeType.STRING},<br>          billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,<br>          pointInTimeRecoverySpecification: {<br>            pointInTimeRecoveryEnabled: true,<br>          },<br>          removalPolicy: isPrd(props.environment)<br>            ? RemovalPolicy.RETAIN<br>            : RemovalPolicy.DESTROY,<br>        },<br>      );<br>    }<br>}</pre><p>We define multiple GSIs within the same stack to support all the required access patterns for the customer table.</p><pre>    [<br>      &#39;GSI1&#39;,<br>      &#39;GSI2&#39;,<br>      &#39;GSI3&#39;,<br>      &#39;GSI4&#39;,<br>    ].forEach(gsi =&gt; {<br>      this.customerTable.addGlobalSecondaryIndex({<br>        indexName: gsi,<br>        partitionKey: {name: `${gsi}PK`, type: dynamodb.AttributeType.STRING},<br>        sortKey: {name: `${gsi}SK`, type: dynamodb.AttributeType.STRING},<br>      });<br>    });</pre><p>If we attempted to deploy this stack as-is, the deployment would fail with the error: <em>“Cannot perform more than one GSI creation or deletion in a single update.”</em><br>To work around this, we’d need to add each GSI in a separate deployment. That means creating one PR per GSI, waiting for it to be reviewed, approved, and merged into main, then promoting the build through each environment to production before starting on the next GSI like so:</p><p>Create MR #1 with the following change, approve, merge and promote to production.</p><pre>[<br>  &#39;GSI1&#39;,<br>].forEach(gsi =&gt; {<br>  this.customerTable.addGlobalSecondaryIndex({<br>    indexName: gsi,<br>    partitionKey: {name: `${gsi}PK`, type: dynamodb.AttributeType.STRING},<br>    sortKey: {name: `${gsi}SK`, type: dynamodb.AttributeType.STRING},<br>  });<br>});</pre><p>Create MR #2 with the following change, approve, merge and promote to production.</p><pre>[<br>  &#39;GSI1&#39;,<br>  &#39;GSI2&#39;,<br>].forEach(gsi =&gt; {<br>  this.customerTable.addGlobalSecondaryIndex({<br>    indexName: gsi,<br>    partitionKey: {name: `${gsi}PK`, type: dynamodb.AttributeType.STRING},<br>    sortKey: {name: `${gsi}SK`, type: dynamodb.AttributeType.STRING},<br>  });<br>});</pre><p>And so on until all GSIs have been created, reviewed, approved and promoted to production.</p><h3>Failure and Recovery Challenges with Multiple GSIs in a Stack</h3><p>The one-GSI-per-update limit doesn’t just slow down schema changes — it can also turn a disaster recovery scenario into a serious headache.</p><p>Imagine this:</p><ul><li>Your DynamoDB table somehow gets deleted or corrupted beyond repair.</li><li>You need to recreate it from scratch by re-deploying your CDK stack.</li><li>The stack definition contains the table plus all of its GSIs in one resource definition.</li></ul><p>On paper, this sounds fine — CloudFormation should just create the table and all the indexes at once, right? Unfortunately, that’s not how DynamoDB works.</p><p>Because DynamoDB only allows one GSI to be created at a time, the stack creation will fail if multiple GSIs are defined on a brand-new table resource. The deployment won’t proceed until you remove all but one GSI from the stack definition — forcing you to manually:</p><ol><li>Edit your infrastructure code to deploy the table with just one GSI.</li><li>Wait for that deployment to complete.</li><li>Add the next GSI, redeploy, repeat until all indexes are rebuilt.</li></ol><p>In a high-pressure recovery situation, this manual, iterative process:</p><ul><li><strong>Delays service restoration</strong> — especially if backfill times are long.</li><li><strong>Introduces human error</strong> when rapidly editing infrastructure code.</li><li><strong>Breaks automated deployments</strong> if your CI/CD pipeline assumes the full table definition is always deployable.</li></ul><p>The one-GSI-per-update limit isn’t just a development inconvenience — it has direct implications for operational resilience. If you manage DynamoDB tables via CDK, you need a plan for how to recreate indexes in a controlled, staged way during recovery.</p><h3>Solutions for Managing the One-GSI-Per-Update Limit</h3><p>Now that we’ve seen how the one-GSI-per-update limit can cause pain in both day-to-day development and disaster recovery, let’s explore two practical ways to work around it — one simple and manual, the other fully automated.</p><h3>1. The Simple Option: Create GSIs Manually in the AWS Console</h3><p>The most straightforward workaround is to remove GSI definitions from your CDK table resource and create them manually via the AWS Management Console, AWS CLI, or SDK after the table is deployed.</p><p>In this approach:</p><ol><li>The CDK stack provisions only the base DynamoDB table (no GSIs).</li><li>Developers or operators manually create the required GSIs one at a time in the AWS Console.</li><li>Once all indexes are built, they’re ready for application use.</li></ol><p><strong>Pros:</strong></p><ul><li>Easy to implement — no code changes needed.</li><li>Ideal for quick experiments or small teams.</li></ul><p><strong>Cons:</strong></p><ul><li>Not automated — requires human action, which slows down deployments.</li><li>Harder to track infrastructure state in version control.</li><li>Inconsistent environments if someone forgets to create an index.</li></ul><h3>2. The Automated Option: Scripted Sequential GSI Creation</h3><p>For production environments or teams practicing Infrastructure as Code, a better solution is to automate GSI creation outside of CloudFormation while keeping the process repeatable.</p><p>The idea:</p><ul><li>Use the AWS SDK (JavaScript, Python, etc.) to script the creation of each GSI one at a time.</li><li>After creating a GSI, poll the table status with DescribeTable until the index is ACTIVE.</li><li>Once active, move on to the next GSI.</li></ul><p><strong>Example flow:</strong></p><ol><li>Deploy the base table using CDK (no GSIs).</li><li>Run the GSI creation script — could be invoked manually, in a CI/CD pipeline, or triggered by a post-deployment step.</li><li>Script calls updateTable for GSI #1 → waits until status = ACTIVE.</li><li>Script repeats for GSI #2, and so on.</li></ol><p><strong>Pros:</strong></p><ul><li>Fully automates index creation while respecting DynamoDB’s service limits.</li><li>Ensures consistent environments — no forgotten GSIs.</li><li>Can be run during initial provisioning and during disaster recovery.</li></ul><p><strong>Cons:</strong></p><ul><li>Slightly more complex to set up than manual creation.</li><li>Still requires multiple sequential creation steps — total creation time is the sum of all GSI backfills.</li></ul><p>The following example script demonstrates how to create GSIs one at a time, waiting for each to become ACTIVE before proceeding:</p><pre>// create-gsis-sequentially.ts<br>import {<br>  DynamoDBClient,<br>  DescribeTableCommand,<br>  UpdateTableCommand,<br>  GlobalSecondaryIndexDescription,<br>  KeySchemaElement,<br>} from &quot;@aws-sdk/client-dynamodb&quot;;<br><br>// ---------- Config ----------<br>const REGION = process.env.AWS_REGION ?? &quot;eu-west-1&quot;;<br>const TABLE_NAME = process.env.TABLE_NAME ?? &quot;CustomerTable&quot;;<br><br>// Define your GSIs here (order matters)<br>const GSIS: Array&lt;{<br>  IndexName: string;<br>  PartitionKey: { name: string; type: &quot;S&quot; | &quot;N&quot; | &quot;B&quot; };<br>  SortKey?: { name: string; type: &quot;S&quot; | &quot;N&quot; | &quot;B&quot; };<br>  Projection:<br>    | { ProjectionType: &quot;ALL&quot; }<br>    | { ProjectionType: &quot;KEYS_ONLY&quot; }<br>    | { ProjectionType: &quot;INCLUDE&quot;; NonKeyAttributes: string[] };<br>  // Only used if the table is provisioned. Omit for on-demand.<br>  ProvisionedThroughput?: { ReadCapacityUnits: number; WriteCapacityUnits: number };<br>}&gt; = [<br>  {<br>    IndexName: &quot;GSI1&quot;,<br>    PartitionKey: { name: &quot;PK&quot;, type: &quot;S&quot; },<br>    SortKey: { name: &quot;SK&quot;, type: &quot;S&quot; },<br>    Projection: { ProjectionType: &quot;ALL&quot; },<br>  },<br>  {<br>    IndexName: &quot;GSI2&quot;,<br>    PartitionKey: { name: &quot;PK&quot;, type: &quot;S&quot; },<br>    SortKey: { name: &quot;SK&quot;, type: &quot;S&quot; },<br>    Projection: { ProjectionType: &quot;INCLUDE&quot;, NonKeyAttributes: [&quot;name&quot;, &quot;lastLogin&quot;] },<br>  },<br>];<br><br>// ---------- Helpers ----------<br>const client = new DynamoDBClient({ region: REGION });<br><br>const sleep = (ms: number) =&gt; new Promise((r) =&gt; setTimeout(r, ms));<br><br>async function getTableDesc() {<br>  const { Table } = await client.send(new DescribeTableCommand({ TableName: TABLE_NAME }));<br>  if (!Table) throw new Error(`Table ${TABLE_NAME} not found`);<br>  return Table;<br>}<br><br>function indexExists(<br>  indexes: GlobalSecondaryIndexDescription[] | undefined,<br>  name: string<br>) {<br>  return Boolean(indexes?.some((g) =&gt; g.IndexName === name));<br>}<br><br>function gsiStatus(<br>  indexes: GlobalSecondaryIndexDescription[] | undefined,<br>  name: string<br>): string | undefined {<br>  return indexes?.find((g) =&gt; g.IndexName === name)?.IndexStatus;<br>}<br><br>function toKeySchema(def: typeof GSIS[number]): KeySchemaElement[] {<br>  const ks: KeySchemaElement[] = [<br>    { AttributeName: def.PartitionKey.name, KeyType: &quot;HASH&quot; },<br>  ];<br>  if (def.SortKey) ks.push({ AttributeName: def.SortKey.name, KeyType: &quot;RANGE&quot; });<br>  return ks;<br>}<br><br>type BillingMode = &quot;PAY_PER_REQUEST&quot; | &quot;PROVISIONED&quot;;<br><br>// ---------- Core logic ----------<br>async function ensureAttributesDefined(attrNames: Array&lt;{ name: string; type: &quot;S&quot; | &quot;N&quot; | &quot;B&quot; }&gt;) {<br>  // CloudFormation usually manages AttributeDefinitions, but when calling UpdateTable directly<br>  // we must ensure attributes referenced by the GSI key schema are in AttributeDefinitions.<br>  const table = await getTableDesc();<br>  const existing = new Map(table.AttributeDefinitions?.map((a) =&gt; [a.AttributeName!, a.AttributeType!]));<br>  const missing = attrNames.filter(a =&gt; existing.get(a.name) !== a.type);<br><br>  if (missing.length) {<br>    // DynamoDB allows updating AttributeDefinitions to ADD new ones (not modify existing types).<br>    // We only add missing ones with correct types.<br>    const newDefs = [<br>      ...(table.AttributeDefinitions ?? []),<br>      ...missing.map(a =&gt; ({ AttributeName: a.name, AttributeType: a.type })),<br>    ];<br><br>    // No-op if nothing truly new (guarded above), but just in case:<br>    await client.send(new UpdateTableCommand({<br>      TableName: TABLE_NAME,<br>      AttributeDefinitions: newDefs,<br>    }));<br>  }<br>}<br><br>async function createGsiSequentially() {<br>  const table = await getTableDesc();<br>  const billingMode = (table.BillingModeSummary?.BillingMode ?? &quot;PROVISIONED&quot;) as BillingMode;<br><br>  for (const gsi of GSIS) {<br>    let t = await getTableDesc();<br>    if (indexExists(t.GlobalSecondaryIndexes, gsi.IndexName)) {<br>      const st = gsiStatus(t.GlobalSecondaryIndexes, gsi.IndexName);<br>      console.log(`Skipping ${gsi.IndexName} (exists, status=${st}).`);<br>      if (st !== &quot;ACTIVE&quot;) await waitForIndexActive(gsi.IndexName);<br>      continue;<br>    }<br><br>    // Make sure key attributes are declared<br>    await ensureAttributesDefined(<br>      [gsi.PartitionKey, ...(gsi.SortKey ? [gsi.SortKey] : [])]<br>    );<br><br>    // Build the create request<br>    const create = {<br>      IndexName: gsi.IndexName,<br>      KeySchema: toKeySchema(gsi),<br>      Projection: gsi.Projection,<br>      ...(billingMode === &quot;PROVISIONED&quot; &amp;&amp; gsi.ProvisionedThroughput<br>        ? { ProvisionedThroughput: gsi.ProvisionedThroughput }<br>        : {}), // omit for on-demand<br>    };<br><br>    console.log(`Creating ${gsi.IndexName}...`);<br>    await client.send(<br>      new UpdateTableCommand({<br>        TableName: TABLE_NAME,<br>        GlobalSecondaryIndexUpdates: [{ Create: create }],<br>      })<br>    );<br><br>    await waitForIndexActive(gsi.IndexName);<br>  }<br><br>  console.log(&quot;All GSIs ensured and ACTIVE ✅&quot;);<br>}<br><br>async function waitForIndexActive(indexName: string, timeoutMs = 1000 * 60 * 60) {<br>  const start = Date.now();<br>  let attempt = 0;<br><br>  while (true) {<br>    const t = await getTableDesc();<br>    const status = gsiStatus(t.GlobalSecondaryIndexes, indexName);<br>    if (status === &quot;ACTIVE&quot;) {<br>      console.log(`${indexName} is ACTIVE.`);<br>      return;<br>    }<br><br>    const tableStatus = t.TableStatus;<br>    console.log(<br>      `[${new Date().toISOString()}] Waiting for ${indexName} to become ACTIVE (indexStatus=${status}, tableStatus=${tableStatus})`<br>    );<br><br>    if (Date.now() - start &gt; timeoutMs) {<br>      throw new Error(`Timed out waiting for ${indexName} to become ACTIVE`);<br>    }<br><br>    // Exponential-ish backoff (cap at ~30s)<br>    const delay = Math.min(1000 * Math.pow(1.5, attempt++), 30_000);<br>    await sleep(delay);<br>  }<br>}<br><br>// ---------- Run ----------<br>createGsiSequentially().catch((err) =&gt; {<br>  console.error(&quot;Failed to create GSIs:&quot;, err);<br>  process.exit(1);<br>});</pre><p>The post deployment script could then be used in the CI/CD pipeline to ensure all GSIs are created during deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5m0kJk-e6t2Z4iACjwy4zA.png" /></figure><p><strong>Recommendation:</strong><br>For small, one-off tables, the manual method might be fine. But for serious production workloads, the scripted approach ensures consistency, reduces human error, and integrates better with automated deployments and recovery plans.</p><h3>Closing Thoughts</h3><p>The one-GSI-per-update limit in DynamoDB isn’t just a technical curiosity — it’s a constraint that can shape how you design, deploy, and recover your database infrastructure. When you’re working in CDK, this limit becomes especially important, as every schema change runs through CloudFormation and inherits the same restriction.</p><p>For small projects or quick experiments, creating GSIs manually in the AWS Console can be enough. But for production workloads — especially those with strict CI/CD pipelines, disaster recovery requirements, and multiple environments — automation is your best ally.</p><p>By separating table creation from index creation and using a sequential, automated approach, you can:</p><ul><li>Respect DynamoDB’s operational limits.</li><li>Keep environments consistent.</li><li>Avoid painful multi-day deployments or recovery delays.</li></ul><p>Ultimately, understanding this limitation early lets you design your stacks and workflows in a way that prevents last-minute surprises, reduces operational risk, and keeps your development velocity high — even when your data model evolves.</p><p>Plan for it now, and you’ll thank yourself later.<strong> 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ec5d08ddd3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Granular Authorisation with Cedar — High Control, Minimal Cost ⚡]]></title>
            <link>https://jcdubs.medium.com/serverless-granular-authorisation-with-cedar-high-control-minimal-cost-1149640f8cd9?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/1149640f8cd9</guid>
            <category><![CDATA[avp]]></category>
            <category><![CDATA[cedar]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 13:34:54 GMT</pubDate>
            <atom:updated>2025-03-09T13:34:54.234Z</atom:updated>
            <content:encoded><![CDATA[<h3>Serverless Granular Authorisation with Cedar — High Control, Minimal Cost 🔐⚡💰</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCE_kC94d1tnosDhq1Iidg.jpeg" /></figure><p>In this blog post, I introduce a granular authorisation pattern for Serverless workloads using the Cedar policy language — achieving fine-grained access control without the high costs of Amazon Verified Permissions.</p><p>If you’ve ever built an application that needed to manage who gets access to what, you’ve probably had your fair share of headaches. Authorisation can get complicated fast, especially when you need fine-grained control beyond simple role-based access. That’s where the <strong>Serverless Granular Authorisation Pattern</strong> comes in — a robust and standardised approach designed to handle complex access control needs in a scalable way.</p><h3>Why Authorisation Matters</h3><p>Before we dive into the pattern, let’s set the stage. Authorisation is about making sure that users (or systems) have the right permissions to perform actions on specific resources. It’s the step that follows authentication — once you’ve proven who you are, what can you actually do?</p><p>A good authorisation system is key for:</p><ul><li><strong>Security</strong> — keeping sensitive data protected.</li><li><strong>Compliance</strong> — meeting regulatory requirements like GDPR and HIPAA.</li><li><strong>Data Integrity</strong> — ensuring only authorised users can modify data.</li><li><strong>Access Control</strong> — giving users the right level of access without overexposing information.</li></ul><h3>The Problem with Hardcoded Authorisation Logic</h3><p>Many teams hardcode authorisation details directly into their codebase, embedding roles, permissions, and access rules within application logic. While this might work initially, it quickly becomes unmaintainable as:</p><ul><li>Business requirements change, leading to constant code modifications.</li><li>Authorisation logic gets duplicated across multiple services.</li><li>Developers need to deploy new versions just to update access rules.</li><li>Debugging and auditing become cumbersome.</li></ul><h3>The Problem with Storing Access Logic in Database Records</h3><p>Another common but flawed approach is storing authorisation logic within database records themselves, where each record defines who can read or modify it. While this might seem like a flexible solution, it actually introduces a host of problems:</p><ul><li><strong>Mixing data with access control</strong> — Authorisation logic should be separate from business data. Embedding it in records makes access control decisions tightly coupled with data models, making changes difficult and error-prone.</li><li><strong>Complexity in auditing and debugging</strong> — When access logic is hidden inside database records, it becomes much harder to track access control issues, leading to inconsistencies and security risks.</li><li><strong>Difficult policy enforcement</strong> — When each record manages its own access, enforcing organisation-wide policies becomes a nightmare, as access rules become fragmented and hard to govern.</li></ul><p>Just like hardcoding authorisation logic in the codebase, embedding it in database records creates an inflexible and unscalable system.</p><h3>Amazon Verified Permissions (AVP) — The Cost Dilemma</h3><p>Originally, the pattern considered <strong>Amazon Verified Permissions (AVP)</strong>, a managed service offering fine-grained access control. AVP is powerful, supporting central policy management and dynamic authorisation checks via APIs. However, <strong>cost became a major roadblock</strong> — at scale, AVP quickly became too expensive compared to alternatives.</p><p>AVP offers tiered pricing based on the volume of authorisation requests and policy management actions made by applications. Specifically, the cost is determined by how many times an app checks whether a principal (user or entity) is allowed to perform a certain action on a resource, as well as the number of policy management API requests.</p><p>We can assess the cost of AVP by calculating its expenses in a typical cloud workload, such as an API Gateway distribution supported by a Lambda function. The following cost analysis focuses specifically on comparing the expenses of API Gateway with those of AVP.</p><p>The cost for AVP and API Gateway are as follows:</p><h4>Amazon Verified Permissions</h4><ul><li><strong>Authorisation Requests</strong>: $0.00015 per request for the first 40 million requests per month.</li><li><strong>Policy Management Requests</strong>: These are additional and vary based on usage.</li></ul><h4>AWS API Gateway</h4><ul><li><strong>Requests</strong>: $3.50 per million requests.</li><li><strong>Data Transfer</strong>: Additional costs based on the amount of data transferred.</li><li><strong>Caching</strong>: Optional, with additional costs if used.</li></ul><h4>Example Cost Comparison for 1 Million Requests:</h4><ol><li><strong>Amazon Verified Permissions</strong>:<br>Authorisation Requests: $0.00015 * 1,000,000 = $150.</li><li><strong>AWS API Gateway</strong>:<br>Requests: $3.50 per million requests = $3.50.</li></ol><h4>Example Cost Comparison for 10 Million Requests:</h4><ol><li><strong>Amazon Verified Permissions</strong>:<br>Authorisation Requests: $0.00015 * 10,000,000 = $1,500.</li><li><strong>AWS API Gateway</strong>:<br>Requests: $3.50 * 10 = $35.</li></ol><h4>Example Cost Comparison for 40 Million Requests:</h4><ol><li><strong>Amazon Verified Permissions</strong>:<br>Authorisation Requests: $0.00015 * 40,000,000 = $6,000.</li><li><strong>AWS API Gateway</strong>:<br>Requests: $3.50 * 40 = $140.</li></ol><p>Given the significant cost difference, especially as the number of requests increases, Amazon Verified Permissions can be much more expensive than AWS API Gateway. <strong>Therefore, Amazon Verified Permissions has not been chosen for this pattern</strong>.</p><h3>Enter Cedar</h3><p><a href="https://docs.cedarpolicy.com/">Cedar</a> is an open source, high-level policy language designed to manage access control in cloud environments. It allows developers and administrators to define policies that govern who can access resources and under what conditions. Key functionalities of Cedar include:</p><ol><li><strong>Declarative Syntax</strong>: Cedar uses a clear and expressive syntax that enables users to write policies in a straightforward manner, making it easier to understand and maintain.</li><li><strong>Attribute-Based Access Control (ABAC)</strong>: Cedar supports ABAC, allowing policies to be based on user attributes, resource attributes, and environmental conditions. This flexibility enables more granular and context-aware access control.</li><li><strong>Hierarchical Policies</strong>: Cedar allows the creation of hierarchical policies, enabling users to define broad policies and then refine them for specific cases or users, facilitating better policy organisation and management.</li><li><strong>Policy Evaluation</strong>: The language includes built-in mechanisms for evaluating policies against requests, ensuring that access decisions are made consistently and efficiently.</li><li><strong>Integration with Cloud Services</strong>: Cedar is designed to integrate seamlessly with cloud services, making it suitable for modern cloud-native applications that require robust and flexible access control mechanisms.</li></ol><p>Overall, Cedar provides a powerful and versatile framework for defining and managing access control policies in complex cloud environments. Amazon Verified Permissions (AVP) utilises Cedar as its underlying policy language for managing access control within cloud applications.</p><p>Cedar enables users to define access control policies in a high-level, declarative format. AVP leverages Cedar’s syntax and capabilities to allow organisations to create sophisticated authorisation rules tailored to their specific needs. AVP provides a centralised service for managing permissions across various AWS services, using Cedar to evaluate policies.</p><p>This centralisation helps streamline access control management, reducing the complexity of permissions scattered across different services. When a request for access is made, AVP uses Cedar to evaluate the relevant policies. This process ensures that access decisions are consistent and based on the latest policy definitions. By employing Cedar, AVP integrates seamlessly with other AWS services, providing developers with a robust framework for implementing fine-grained access control in cloud applications.</p><p>Although the decision was made to forgo using AVP in this pattern due to its high cost, there remains an opportunity to leverage the functionality and benefits offered by Cedar, which AVP utilises. Although Cedar policies and schemas are written in a high-level, declarative language specifically designed for expressing access control policies, the Cedar evaluation engine is written in the Rust programming language.</p><p>This presents a challenge for teams with limited or no experience in Rust, as well as those without any services written in Rust, making it difficult for them to utilise the Cedar evaluation engine directly. Fortunately, Cedar offers a WebAssembly (WASM) module that enables the integration of the Cedar evaluation engine with other programming languages, such as TypeScript.</p><h4>Sample Cedar Policy</h4><p>To illustrate, here’s an example of a Cedar policy allowing customers to view their own orders:</p><pre>permit (<br>    principal,<br>    action in [OrderService::Action::&quot;getOrder&quot;, OrderService::Action::&quot;listOrders&quot;],<br>    resource<br>)<br>when {<br>    resource.customer == principal &amp;&amp;<br>    principal in OrderService::Role::&quot;customers&quot;<br>};</pre><p>This policy ensures that users can only access orders if they’re the customer associated with them.</p><h3>The Serverless Granular Authorisation Approach</h3><p>The <strong>Serverless Granular Authorisation Pattern</strong> separates authorisation logic from business logic, making access control centralised, dynamic, and maintainable.</p><p>Instead of hardcoding permissions, this pattern leverages Cedar policy language to define access rules in external policy documents. These policies are stored centrally and retrieved at runtime, ensuring that authorisation decisions remain flexible and easy to update without touching application code.</p><p>The pattern uses a combination of:</p><ul><li><strong>RBAC (Role-Based Access Control)</strong> — Assigns broad access levels based on roles (e.g., admin, manager, user).</li><li><strong>ABAC (Attribute-Based Access Control)</strong> — Uses attributes like department, location, or project ownership to refine permissions.</li><li><strong>Context-Based Authorisation</strong> — Incorporates transient, request-specific information such as time of access, IP address, or authentication method to make dynamic access decisions.</li></ul><p>By integrating these approaches, the Serverless Granular Authorisation Pattern ensures that access control is both precise and adaptable to varying scenarios.</p><h4>How It Works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x2dybmFEwCB7whKxHzfbgw.png" /></figure><p>Here’s a simple breakdown of how the Serverless Granular Authorisation Pattern functions within a cloud service:</p><ol><li><strong>User logs in</strong> — Authentication happens via an Identity Provider (IDP), issuing a JWT token.</li><li><strong>API call is made</strong> — The user sends a request, including their JWT token.</li><li><strong>API endpoint</strong> — The <strong>API Gateway</strong> processes the incoming request from the user, which includes their <strong>JWT token</strong> for authentication.</li><li><strong>Gateway validation</strong> — The API Gateway and Cognito authoriser confirm the token is valid.</li><li><strong>Authorisation check</strong> — The Lambda function retrieves the relevant Cedar policy and schema. The Cedar evaluation engine determines if the action is allowed. The request is either processed or rejected based on policy rules.</li></ol><h3>Deployment &amp; Scalability</h3><p>By separating authorisation from application code, this pattern makes it easier to manage access policies across multiple services without code changes. The pattern is implemented using:</p><ul><li><strong>Cedar Lambda Layer</strong> — A reusable module containing the Cedar dynamic authorisation engine provided through the cedar WASM module.</li><li><strong>CDK Constructs</strong> — Infrastructure as code for deploying policies to an <strong>S3-based central policy store</strong>.</li><li><strong>SDK Middleware</strong> — Making it easy to plug authorisation logic into APIs.</li></ul><p>The use of caching and lightweight Lambda layers keeps performance optimised, avoiding latency spikes.</p><h3>The Cost Factor</h3><p>Unlike AVP, the Serverless Granular Authorisation Pattern minimises costs by:</p><ul><li>Using S3 for policy storage instead of an expensive managed policy engine.</li><li>Running Cedar policy evaluations within Lambda, avoiding per-request fees.</li><li>Allowing teams to manage policies independently, reducing developer effort.</li></ul><h3>Demonstration: Implementing the Serverless Granular Authorisation pattern in an Order Service REST API</h3><p>Next up, we’ll see how to bring this pattern to life in an Order Service API that handles company orders through CRUD endpoints. This service already has authentication covered with Amazon Cognito and a Cognito API Gateway Authoriser. If you want to follow along, you can check out the code in the accompanying Git repository.</p><p><a href="https://github.com/JCDubs/serverless-cedar-authorisation">GitHub - JCDubs/serverless-cedar-authorisation</a></p><p>The pattern involves setting up common resources, a common CDK npm module, and a common SDK npm module. To keep things simple, these have been organised as separate directories within the Git repository. Each directory should be built or deployed in the order outlined in this blog post to ensure everything integrates smoothly.</p><pre>ROOT<br>  |<br>  | -&gt; common-resources // Common resources depoloyed to a central tools account. <br>  | -&gt; common-cdk       // Common CDK construct that manages the upload of policy files.<br>  | -&gt; common-sdk       // Common SDK modules providing authrorisation logic.<br>  | -&gt; order-service    // The Order service API project that implements the pattern.</pre><p>Lets look at each of these directories one by one.</p><h3>Common Resources</h3><p>The pattern requires a couple of common resources deployed to a central tools account — a central policy store S3 bucket and a Lambda layer containing the Cedar WASM package.</p><p><strong>Central Policy Store S3 Bucket:</strong></p><p>The central policy store is a private S3 bucket set up with a bucket policy that lets all organisational accounts upload and retrieve Cedar policy and schema files. To keep things organised, the bucket follows a naming convention: it includes the organisation’s name with a “policy-store” suffix. Policy files are stored using a structured path, with each service’s policies placed under {service}/policy. Sticking to these naming conventions makes it easier to integrate with other common CDK and SDK modules, keeping everything consistent and scalable.</p><p><strong>Cedar Lambda Layer:</strong></p><p>As we touched on earlier, Cedar provides a WASM module that lets non-Rust projects take advantage of its dynamic authorisation engine. This means we can use Cedar in TypeScript projects — but there’s a catch. The Esbuild bundler used in AWS CDK’s Node.js Lambda construct doesn’t support including WASM modules out of the box. While raw Esbuild does have ways to bundle WASM, the CDK’s version doesn’t. To get around this, we package the Cedar WASM module into a Lambda Layer, ensuring it’s available for our Lambda functions at runtime.</p><p><strong>Deployment:</strong></p><p>As mentioned earlier, common resources should ideally be deployed to a central tools AWS account. However, for testing purposes, you can deploy them in the same AWS account as your Order Service. This makes it easier to experiment and validate everything before rolling it out centrally.</p><h3>Common CDK Module</h3><p>The common CDK module includes a handy construct called AuthPolicyStore, which makes it easy for service projects to interact with the central policy store. It allows services to retrieve a reference to the S3 bucket and upload their Cedar policy and schema files as part of the deployment process—keeping everything streamlined and automated.</p><pre>const AUTH_POLICY_STORE_BUCKET_SUFFIX = &#39;auth-policy-store&#39;;<br><br>export class AuthPolicyStore extends Resource {<br>  readonly policyStoreBucket: s3.IBucket;<br><br>  constructor(<br>    scope: Construct,<br>    id: string,<br>    { policyDirectoryPath, serviceName, organisationName }: PolicyStoreProps<br>  ) {<br>    super(scope, id);<br>    // Retrieve the <br>    this.policyStoreBucket = s3.Bucket.fromBucketName(<br>      this,<br>      &#39;CentralAuthBucket&#39;,<br>      `${organisationName}-${AUTH_POLICY_STORE_BUCKET_SUFFIX}`<br>    );<br><br>    new BucketDeployment(this, &#39;PolicyDeployments&#39;, {<br>      destinationBucket: this.policyStoreBucket,<br>      sources: [Source.asset(policyDirectoryPath)],<br>      destinationKeyPrefix: `${serviceName}/policy`,<br>    });<br>  }<br>}</pre><p>The construct requires three properties:</p><ul><li><strong>policyDirectoryPath</strong>: The directory path of the directory containing the Cedar policy and schema files.</li><li><strong>serviceName</strong>: The name of the service the policy files belong to.</li><li><strong>organisationName</strong>: The name of the organisation.</li></ul><p>These properties help connect to the central policy store bucket and ensure that each service’s Cedar policy and schema files are uploaded using a consistent naming convention — making access control structured and easy to manage.</p><h3>Common SDK Module</h3><p>The common SDK module simplifies the use of the Serverless Granular Authorisation Pattern by handling most of the heavy lifting. It provides the following built-in services to make implementation easier:</p><h4><strong>User Details Service:</strong></h4><p>The UserDetailService pulls key details from the authoriser claims in an APIGatewayProxyEvent, extracting the username of the calling user and their associated roles. It then stores this information, making it easily accessible for other services during Lambda invocations.</p><pre>...<br><br>/**<br>* Set the user details from the event.<br>* @param authenticatedEvent The request event containing the authentication details.<br>*/<br>static setUserDetails(authenticatedEvent: APIGatewayProxyEvent) {<br>if (!authenticatedEvent.requestContext.authorizer) {<br>  logger.warn(&#39;The event is not an authenticated request.&#39;);<br>  return;<br>}<br>logger.debug(&#39;Getting user name...&#39;);<br>this.userName = authenticatedEvent.requestContext.authorizer.claims[&#39;cognito:username&#39;];<br>logger.debug(&#39;User name set.&#39;, { userName: this.userName });<br>if (typeof authenticatedEvent.requestContext.authorizer.claims[&#39;cognito:groups&#39;] === &#39;string&#39;) {<br>  this.roles = [];<br>  this.roles.push(authenticatedEvent.requestContext.authorizer.claims[&#39;cognito:groups&#39;]);<br>} else {<br>  this.roles = authenticatedEvent.requestContext.authorizer.claims[&#39;cognito:groups&#39;];<br>}<br>logger.debug(&#39;User details set&#39;, {<br>  userName: this.userName,<br>  roles: this.roles,<br>});<br>}<br><br>...</pre><h4><strong>Authorisation Service</strong></h4><p>The AuthorisationService streamlines access control with three key functions: retrieving and caching Cedar policy files from the central S3 bucket, building a Cedar-compliant authorisation requests, and sending the requests to the Cedar authorisation engine for real-time access decisions.</p><pre>...<br><br>const AUTH_POLICY_STORE_BUCKET_SUFFIX = &#39;auth-policy-store&#39;;<br>const POLICY_FILE_NAME = &#39;policies.cedar&#39;;<br>const SCHEMA_FILE_NAME = &#39;schema.cedarschema&#39;;<br><br>...<br><br>export class AuthorizationService {<br>  private static s3Client: S3Client;<br>  private static service: AuthorizationService;<br>  private readonly authorizationConfig: AuthorizationConfigType;<br>  private readonly policy: string;<br>  private readonly schema: string;<br>  private action: string | undefined;<br>  private resource: string | undefined;<br>  private context: Record&lt;string, cedar.CedarValueJson&gt; | undefined;<br>  private entities: cedar.EntityJson[] | undefined;<br><br>  /**<br>   * Create an instance of the Authorization service.<br>   * @param policy The cedar policy to use when evaluating requests.<br>   * @param schema The cedar schema to use when evaluating requests.<br>   * @param authorizationConfig The service authorization configuration.<br>   */<br>  private constructor(<br>    policy: string,<br>    schema: string,<br>    authorizationConfig: AuthorizationConfigType<br>  ) {<br>    this.policy = policy;<br>    this.schema = schema;<br>    this.authorizationConfig = authorizationConfig;<br>  }<br><br>  /**<br>   * Set the action the user is attempting to perform.<br>   * @param action User request action.<br>   * @returns AuthorizationService.<br>   */<br>  setAction(action: string): AuthorizationService {<br>    this.action = action;<br>    return this;<br>  }<br><br>  /**<br>   * Set the Cedar resource name the user is attempting to perform the request on.<br>   * @param resource The Cedar resource.<br>   * @returns AuthorizationService<br>   */<br>  setResource(resource: string): AuthorizationService {<br>    this.resource = resource;<br>    return this;<br>  }<br><br>  /**<br>   * Add an entity to the Cedar authorization request.<br>   * @param entity The entity to add to the Cedar authorization request.<br>   * @returns AuthorizationService<br>   */<br>  addEntity(entity: cedar.EntityJson): AuthorizationService {<br>    if (!this.entities) {<br>      this.entities = [];<br>    }<br>    this.entities.push(entity);<br>    return this;<br>  }<br><br>  /**<br>   * Set an array of entities to use in the Cedar authorization request.<br>   * @param entities The array of entities.<br>   * @returns AuthorizationService<br>   */<br>  setEntities(entities: cedar.EntityJson[]): AuthorizationService {<br>    this.entities = entities;<br>    return this;<br>  }<br><br>  /**<br>   * Validate the Authorization service authorization properties.<br>   * @throws MissingAuthorizationActionError<br>   * @throws MissingAuthorizationResourceError<br>   * @throws MissingAuthorizationPolicyError<br>   * @throws MissingAuthorizationSchemaError<br>   */<br>  private validateAuthorizationProperties() {<br>    // Validate that a username and roles is available.<br>    if (!UserDetailService.getUserName() || !UserDetailService.getRoles()) {<br>      logger.error(&#39;Authenticated user username or roles has not been provided&#39;);<br>      throw new MissingAuthenticatedUserDetailsError();<br>    }<br><br>    // Validate the cedar scope<br>    if (!this.action) {<br>      logger.error(&#39;Cedar authorization action has not been provided&#39;);<br>      throw new MissingAuthorizationActionError();<br>    }<br><br>    // Validate the cedar scope<br>    if (!this.resource) {<br>      logger.error(&#39;Cedar authorization resource has not been provided&#39;);<br>      throw new MissingAuthorizationResourceError();<br>    }<br>  }<br><br>  /**<br>   * Create the Cedar schema object required by the evaluation process.<br>   * @returns Cedar schema.<br>   */<br>  private createSchema(): cedar.Schema {<br>    try {<br>      const schema = JSON.parse(this.schema);<br>      return { json: schema };<br>    } catch (err) {<br>      return { human: this.schema };<br>    }<br>  }<br><br>  /**<br>   * Construct the Cedar user entity required by the evaluation process.<br>   * @returns Cedar EntityJson<br>   */<br>  private constructUserEntity(): cedar.EntityJson {<br>    return {<br>      uid: {<br>        type: `${this.authorizationConfig.namespace}${this.authorizationConfig.principleType}`,<br>        id: UserDetailService.getUserName()!,<br>      },<br>      attrs: {},<br>      parents:<br>        UserDetailService.getRoles()?.map((role) =&gt; ({<br>          type: `${this.authorizationConfig.namespace}${this.authorizationConfig.roleType}`,<br>          id: role,<br>        })) ?? [],<br>    };<br>  }<br><br>  /**<br>   * Construct the Cedar role entities required by the evaluation process.<br>   * @returns Cedar EntityJson<br>   */<br>  private constructRoleEntities(): cedar.EntityJson[] {<br>    return (<br>      UserDetailService.getRoles()?.map((role) =&gt; ({<br>        uid: {<br>          type: `${this.authorizationConfig.namespace}${this.authorizationConfig.roleType}`,<br>          id: role,<br>        },<br>        attrs: {},<br>        parents: [],<br>      })) ?? []<br>    );<br>  }<br><br>  /**<br>   * Build the Cedar AuthorizationCall object using the values provided to the<br>   * Authorization service factory functions.<br>   * @returns Cedar AuthorizationCall.<br>   */<br>  private build(): cedar.AuthorizationCall {<br>    this.validateAuthorizationProperties();<br><br>    const user = this.constructUserEntity();<br>    const roles = this.constructRoleEntities();<br><br>    return {<br>      principal: {<br>        type: `${this.authorizationConfig.namespace}${this.authorizationConfig.principleType}`,<br>        id: UserDetailService.getUserName()!,<br>      },<br>      action: {<br>        type: `${this.authorizationConfig.namespace}Action`,<br>        id: this.action!,<br>      },<br>      resource: {<br>        type: `${this.authorizationConfig.namespace}${this.authorizationConfig.resourceType}`,<br>        id: this.resource!,<br>      },<br>      context: this.context ?? {},<br>      schema: this.createSchema(),<br>      enableRequestValidation: true,<br>      slice: {<br>        policies: this.policy,<br>        entities: [user, ...(this.entities ?? []), ...roles],<br>        templateInstantiations: [],<br>      },<br>    };<br>  }<br><br>  /**<br>   * Determine whether the user is authorized to perform the requested action based on<br>   * the user&#39;s details, role&#39;s and the action the user is attempting to perform on the entity.<br>   * @returns Whether the user is authorized to perform the requested action.<br>   */<br>  isAuthorized(): boolean {<br>    logger.debug(&#39;Authorizing request...&#39;);<br>    const builtAuthRequest = this.build();<br>    logger.debug(&#39;Built Authorization request&#39;, { builtAuthRequest });<br>    const authResult = cedar.isAuthorized(builtAuthRequest);<br>    logger.debug(&#39;Auth Result&#39;, { authResult });<br><br>    if (authResult.type === &#39;failure&#39;) {<br>      logger.debug(&#39;A problem occurred while authorizing the request&#39;, {<br>        authResult,<br>      });<br>      throw Error(authResult.errors.map((error) =&gt; error.message).join(&#39;\n&#39;));<br>    }<br>    return authResult.response.decision === (&#39;Allow&#39; as cedar.Decision);<br>  }<br><br>  /**<br>   * Get the authorization service.<br>   * A cached instance of the service is returned if the get function has been previously called.<br>   * An instance of the service is created replacing the cached service and re-retrieving the Cedar<br>   * policy and schema from the central S3 bucket if the provided &#39;refresh&#39;<br>   * flag is provided as a {true} boolean value.<br>   * @param authorizationConfig The authorization configuration.<br>   * @param serviceConfig The service configuration.<br>   * @param refresh Whether the policy and schema should be refreshed.<br>   * @returns Promise&lt;AuthorizationService&gt;<br>   */<br>  static async getService(<br>    authorizationConfig: AuthorizationConfigType,<br>    serviceConfig: ServiceConfig,<br>    refresh = false<br>  ): Promise&lt;AuthorizationService&gt; {<br>    if (!refresh &amp;&amp; this.service) {<br>      logger.debug(&#39;Returning cached Authorization service&#39;);<br>      return this.service;<br>    }<br><br>    if (!this.s3Client) {<br>      this.s3Client = new S3Client();<br>    }<br><br>    const bucket = `${serviceConfig.organisationName}-${AUTH_POLICY_STORE_BUCKET_SUFFIX}`;<br>    const keyPrefix = `${serviceConfig.serviceName}/policy`;<br>    let policy: string | undefined;<br>    let schema: string | undefined;<br><br>    try {<br>      policy = await this.s3Client.getObject(`${keyPrefix}/${POLICY_FILE_NAME}`, bucket);<br>    } catch (err) {<br>      logger.error(&#39;Policy is not present in the central authorization S3 Bucket&#39;, { error: err });<br>      throw new MissingAuthorizationPolicyError();<br>    }<br><br>    try {<br>      schema = await this.s3Client.getObject(`${keyPrefix}/${SCHEMA_FILE_NAME}`, bucket);<br>    } catch (err) {<br>      logger.error(&#39;Schema is not present in the central authorization S3 Bucket&#39;, { error: err });<br>      throw new MissingAuthorizationSchemaError();<br>    }<br><br>    if (!policy) {<br>      logger.error(&#39;Policy is not present in the central authorization S3 Bucket&#39;);<br>      throw new MissingAuthorizationPolicyError();<br>    }<br><br>    if (!schema) {<br>      logger.error(&#39;Schema is not present in the central authorization S3 Bucket&#39;);<br>      throw new MissingAuthorizationSchemaError();<br>    }<br><br>    logger.debug(&#39;Policy and Schema loaded&#39;, {<br>      policy,<br>      schema,<br>    });<br>    this.service = new AuthorizationService(policy, schema, authorizationConfig);<br>    return this.service;<br>  }<br>}</pre><p>The factory static getService function ensures that an AuthorisationService instance is available—creating one if needed. It does this by retrieving and caching Cedar policy files from the central S3 bucket, so warm Lambda invocations don’t need to make repeated S3 requests.</p><p>The AuthorisationService class also provides methods for incrementally building an authorisation request, allowing you to specify entities, resources, and actions step by step.</p><p>Once all required values are set, calling isAuthorized constructs a Cedar authorisation request and sends it to the Cedar authorisation engine, determining whether the user is permitted to perform the requested action on the resource.</p><h3>Authorisation Middleware</h3><p>The authorisation-middleware file includes a single function called loadCedarAuthorization, which initialises both the UserDetailService and AuthorisationService when a Lambda function is invoked. This function is designed to be used as Middy middleware, making it easy to integrate the Serverless Granular Authorisation Pattern into any Lambda handler.</p><pre>export const loadCedarAuthorization = (<br>  authorizationConfig: AuthorizationConfigType,<br>  serviceConfig: ServiceConfig<br>): middy.MiddlewareObj&lt;APIGatewayProxyEvent, APIGatewayProxyResult&gt; =&gt; {<br>  const before: middy.MiddlewareFn&lt;APIGatewayProxyEvent, APIGatewayProxyResult&gt; = async (<br>    request<br>  ): Promise&lt;void&gt; =&gt; {<br>    logger.debug(&#39;Loading authorization services...&#39;, {<br>      authorizationConfig,<br>      serviceConfig,<br>    });<br><br>    const refresh =<br>      request.event.headers &amp;&amp; request.event.headers[&#39;cedar-refresh&#39;]<br>        ? request.event.headers[&#39;cedar-refresh&#39;] === &#39;true&#39;<br>        : false;<br><br>    UserDetailService.setUserDetails(request.event);<br>    await AuthorizationService.getService(authorizationConfig, serviceConfig, refresh);<br>  };<br>  logger.debug(&#39;Authorization services loaded and configured.&#39;);<br>  return {<br>    before,<br>  };<br>};</pre><p>All of the common functionality — including common resources, CDK constructs, and SDK modules — is built once and made available for all teams across the organisation. Now, let’s dive into how we can use these shared resources to implement the Serverless Granular Authorisation Pattern in a project.</p><h3>Order Service API</h3><p>The Order Service API is where we’ll apply the Serverless Granular Authorisation Pattern, leveraging all the common resources, CDK constructs, and SDK functionality. We’ll break down the implementation step by step to show how it all comes together.</p><h4>Cedar Policy Documents</h4><p>First, we create a directory called authorisation in the root of the Order Service project. This directory will hold the Cedar policy and schema files. The final directory and file structure looks like this:</p><pre>Order Service ROOT<br>       | -&gt; authorisation<br>                  | -&gt; policies.cedar<br>                  | -&gt; schema.cedarschema</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahSkTX1wP88Wko1kDTHVXw.png" /></figure><p>The Cedar policy and schema files for the Order Service are structured as follows respectively:</p><pre>// Customer Policies<br><br>// Customer can view their own orders<br>permit (<br>    principal,<br>    action in [OrderService::Action::&quot;getOrder&quot;, OrderService::Action::&quot;listOrders&quot;],<br>    resource<br>)<br>when {<br>    resource.customer == principal &amp;&amp;<br>    principal in OrderService::Role::&quot;customers&quot;<br>};<br><br>// Customers can create their own orders<br>permit (<br>    principal,<br>    action in [OrderService::Action::&quot;createOrder&quot;],<br>    resource<br>)<br>when {<br>    resource.createdBy == principal &amp;&amp;<br>    resource.customer == principal &amp;&amp;<br>    principal in OrderService::Role::&quot;customers&quot;<br>};<br><br>// Customers can update and delete any order if the status is a certain value<br>permit (<br>    principal,<br>    action in [OrderService::Action::&quot;updateOrder&quot;, OrderService::Action::&quot;deleteOrder&quot;],<br>    resource<br>)<br>when {<br>    resource.status == &quot;PENDING&quot; &amp;&amp;<br>    resource.createdBy == principal &amp;&amp;<br>    resource.customer == principal &amp;&amp;<br>    principal in OrderService::Role::&quot;customers&quot;<br>};<br><br>// Sales Staff and Sale Managers Policies<br><br>// Sales Staff and Sale Managers can update and delete any order if the status is a certain value<br>permit (<br>    principal,<br>    action in [OrderService::Action::&quot;updateOrder&quot;, OrderService::Action::&quot;deleteOrder&quot;],<br>    resource<br>)<br>when {<br>    resource.status == &quot;PENDING&quot; &amp;&amp;<br>    (principal in OrderService::Role::&quot;saleStaff&quot; || principal in OrderService::Role::&quot;saleManagers&quot;)<br>};<br><br>// Sales Staff and Sale Managers can view and create any orders<br>permit (<br>    principal,<br>    action in [OrderService::Action::&quot;createOrder&quot;, OrderService::Action::&quot;getOrder&quot;, OrderService::Action::&quot;listOrders&quot;],<br>    resource<br>)<br>when {<br>    principal in OrderService::Role::&quot;saleStaff&quot; || principal in OrderService::Role::&quot;saleManagers&quot;<br>};<br><br>// Account Manager Policies<br><br>// Account Managers can view orders for accounts they manage<br>permit (<br>    principal,<br>    action in [OrderService::Action::&quot;getOrder&quot;, OrderService::Action::&quot;listOrders&quot;],<br>    resource<br>)<br>when {<br>    resource.accountManager == principal &amp;&amp;<br>    principal in OrderService::Role::&quot;accountManagers&quot;<br>};<br><br>// Accountant Policies<br><br>// Accountants can view orders for accounts they manage<br>permit (<br>    principal,<br>    action in [OrderService::Action::&quot;getOrder&quot;, OrderService::Action::&quot;listOrders&quot;],<br>    resource<br>)<br>when {<br>    principal in OrderService::Role::&quot;accountants&quot;<br>};</pre><pre>namespace OrderService {<br><br>    entity Role;<br>    entity User in [Role];<br><br>    entity Order = {<br>        createdBy: User,<br>        customer: User,<br>        accountManager: User,<br>        status: String<br>    };<br><br>    action &quot;createOrder&quot; appliesTo {    <br>      principal: [User],    <br>      resource: [Order],    <br>      context: {}    <br>    };<br><br>    action &quot;updateOrder&quot; appliesTo {    <br>      principal: [User],    <br>      resource: [Order],    <br>      context: {}    <br>    };<br><br>    action &quot;deleteOrder&quot; appliesTo {    <br>      principal: [User],    <br>      resource: [Order],    <br>      context: {}    <br>    };<br><br>    action &quot;getOrder&quot; appliesTo {    <br>      principal: [User],    <br>      resource: [Order],    <br>      context: {<br>      }    <br>    };<br><br>    action &quot;listOrders&quot; appliesTo {    <br>      principal: [User],    <br>      resource: [Order],    <br>      context: {<br>      } <br>    };<br>}</pre><p>As you can see, Cedar policy and schema files are clear, readable, and easy to manage, making it simpler to avoid misconfigurations and reduce authorisation errors.</p><p>Next, we retrieve a reference to the central policy store S3 bucket and upload the Cedar policy and schema files using the common CDK AuthPolicyStore construct.</p><pre>...<br><br>export class AuthStack extends cdk.Stack {<br><br>    readonly policyStoreBucket: s3.IBucket;<br><br>    ...<br><br>    this.policyStoreBucket = new AuthPolicyStore(this, &#39;AuthPolicyStore&#39;, {<br>      serviceName: SERVICE,<br>      organisationName: props.organisationName,<br>      policyDirectoryPath: path.resolve(__dirname, &#39;../../../../authorisation&#39;)<br>    }).policyStoreBucket;<br>}</pre><p>We create an implementation of the AuthPolicyStore construct, passing in the service name, organisation name, and the path to the authorisation directory. The central policy store S3 bucket reference is then stored as a class variable, making it available for use in other stacks.</p><h4>Cedar Lambda Layer</h4><p>The next step is to include the Cedar Lambda Layer in all Order Service Lambdas. We do this by creating a reference to the Cedar Lambda Layer using its ARN.</p><pre>export class StatelessStack extends cdk.Stack {<br>  readonly orderAPI: apigw.LambdaRestApi;<br>  <br>  constructor(scope: Construct, id: string, props: OrdersStatelessStackProps) {<br>    super(scope, id, props);<br><br>    const cedarLayer = lambda.LayerVersion.fromLayerVersionArn(this, &#39;CedarLambdaLayer&#39;, props.cedarLambdaLayerARN);<br><br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGbPxCiq3B4xdj8aQshqNA.png" /></figure><p>The Cedar Lambda Layer is then provided to each Order Service Lambda in the following way.</p><pre>const createOrderLambda = this.createOrderAPILambda(<br>  &#39;CreateOrderService&#39;,<br>  &#39;api-create-order-adapter&#39;,<br>  props,<br>  [cedarLayer],<br>);<br>...<br>createOrderAPILambda(<br>    serviceName: string,<br>    entryFileName: string,<br>    props: OrdersStatelessStackProps,<br>    lambdaLayers: lambda.ILayerVersion[],<br>    environmentVariables?: Record&lt;string, string&gt;,<br>  ) {<br>    return new njsLambda.NodejsFunction(this, serviceName, {<br>      functionName: serviceName,<br>      entry: path.resolve(<br>        __dirname,<br>        `../../../../src/adapters/primary/${entryFileName}/${entryFileName}.ts`,<br>      ),<br>      memorySize: 1024,<br>      runtime: lambda.Runtime.NODEJS_20_X,<br>      environment: {<br>        LOG_LEVEL: &#39;DEBUG&#39;,<br>        POWERTOOLS_LOG_LEVEL: &#39;DEBUG&#39;,<br>        TABLE_NAME: props.orderTable.tableName,<br>        COUNTRY: config.country,<br>        DOMAIN: config.domain,<br>        SERVICE_NAME: config.service,<br>        ENVIRONMENT: props.environment,<br>        POWERTOOLS_SERVICE_NAME: serviceName,<br>        ORGANISATION_NAME: props.organisationName,<br>        ...environmentVariables,<br>      },<br>      layers: lambdaLayers,<br>      bundling: {<br>        minify: true,<br>        externalModules: [&#39;@aws-sdk/*&#39;, &#39;@cedar-policy/cedar-wasm/nodejs&#39;],<br>      },<br>    });<br>  }<br>}</pre><p>The createOrderLambda utility function is updated to accept an array of Lambda layers, which are then passed to the Lambda construct via the layers property. Additionally, the Lambda bundling configuration is modified to exclude the @cedar-policy/cedar-wasm/nodejs module, ensuring it is not bundled with the Lambda code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHfINiMX3yC5jftpUwe66A.png" /></figure><h4>Authorisation Middleware</h4><p>Next, we add authorisation configuration objects to the config.ts file.</p><ul><li>The ServiceConfig is used by the AuthorisationService to retrieve policy files from the central policy store S3 bucket.</li><li>The AuthorizationConfigType object defines the namespace, along with the principal, resource, and role types to be used in the authorisation request.</li></ul><pre>import { AuthorizationConfigType, ServiceConfig } from &#39;common-sdk&#39;;<br><br>...<br><br>export const authorizationServiceConfig: ServiceConfig = {<br>  serviceName: config.get(&#39;serviceName&#39;),<br>  organisationName: config.get(&#39;organisationName&#39;),<br>}<br><br>export const authorizationConfig: AuthorizationConfigType = {<br>  namespace: &#39;OrderService::&#39;,<br>  principleType: &#39;User&#39;,<br>  resourceType: &#39;Order&#39;,<br>  roleType: &#39;Role&#39;,<br>};</pre><p>The authorisation configuration in config.ts is used when calling the loadCedarAuthorisation middleware, provided by the common SDK module.</p><p>To integrate this, the wrapper function in the shared/wrapper utility file is updated to include the authorisation middleware, ensuring it uses the correct authorisation configuration.</p><pre>export const wrapper = &lt;T extends Handler&gt;(<br>  handler: T,<br>): middy.MiddyfiedHandler =&gt; {<br>  return middy(handler)<br>    .use(injectLambdaContext(logger))<br>    .use(captureLambdaHandler(tracer))<br>    .use(loadCedarAuthorization(authorizationConfig, authorizationServiceConfig));<br>};</pre><h4>Auth Utils</h4><p>The authorisation request requires a resource entity to be constructed for validation. While entities, resources, and actions in the Cedar policy and schema files vary between services, the resource entity is always service-specific.</p><p>Since an Order resource entity needs to be created each time an Order Lambda is invoked, it makes sense to have a utility function that constructs the Order entity. This function can then be reused across all Lambda functions when generating the authorisation request.</p><pre>import * as cedar from &quot;@cedar-policy/cedar-wasm/nodejs&quot;;<br>import { authorizationConfig } from &#39;@config/config&#39;;<br>import { Order } from &quot;@models/order&quot;;<br><br>/**<br> * Create a Cedar order entity.<br> * @param Order <br> * @returns Order Cedar entity.<br> */<br>export const createOrderEntity = (order: Order): cedar.EntityJson =&gt; {<br>    return {<br>        uid: {<br>            type: `${authorizationConfig.namespace}${authorizationConfig.resourceType}`,<br>            id: order.id,<br>        },<br>        attrs: {<br>            createdBy: {<br>                __entity: {<br>                    type: `${authorizationConfig.namespace}${authorizationConfig.principleType}`,<br>                    id: order.createdBy<br>                }<br>            },<br>            customer: {<br>                __entity: {<br>                    type: `${authorizationConfig.namespace}${authorizationConfig.principleType}`,<br>                    id: order.customer.email<br>                }<br>            },<br>            accountManager: {<br>                __entity: {<br>                    type: `${authorizationConfig.namespace}${authorizationConfig.principleType}`,<br>                    id: order.customer.accountManager<br>                }<br>            },<br>            status: order.status,<br>        },<br>        parents: []<br>    }<br>}</pre><p>The createOrderEntity function is added to the shared/auth-utils directory. It takes an Order object as input and returns a cedar.EntityJson object with the necessary properties for authorisation.</p><p>The cedar.EntityJson object consists of three key properties:</p><ul><li>uuid – A unique identifier defining the type and ID of the entity. In this case, the type is constructed using the namespace and resource type from the authorisation configuration, resulting in: OrderService::Order.</li><li>attrs – Contains order-specific attributes used in policy evaluation, including createdBy, customer, accountManager, and status. Each attribute type is determined using the namespace and principleType from the authorisation configuration, and its value is set based on the provided Order object.</li><li>parents – Defines parent entities, if applicable.</li></ul><p>This function ensures consistency in how Order entities are constructed across all Lambda functions, making authorisation requests dynamic and scalable.</p><h4>Authorisation Adapter</h4><p>Even though each Lambda function in the Order Service handles different action types, they all follow the same process to construct an authorisation request:</p><ol><li>Retrieve the AuthorisationService</li><li>Set the action type, resource, and entities in the service</li><li>Call the isAuthorised function to determine if the user has permission to perform the action</li></ol><p>Since this logic is common across all functions, it’s implemented as a secondary adapter called authoriseRequest, located in the adapters/secondary/authorisation-adapter directory. This keeps the authorisation process consistent, reusable, and easy to maintain.</p><pre>...<br>/**<br> * Determine whether a user is authorised to perform a specific action on an order resource.<br> * @param action The action associated to the authorisation request.<br> * @param order The Order to associate to the request.<br> */<br>export const authoriseRequest = async (action: OrderAuthAction, order: Order): Promise&lt;void&gt; =&gt; {<br>    const authorizationService = await AuthorizationService.getService(authorizationConfig, authorizationServiceConfig)<br>    const authResult = authorizationService<br>        .setAction(action)<br>        .setResource(order.id)<br>        .setEntities([createOrderEntity(order)])<br>        .isAuthorized();<br><br>    logger.debug(`Order Authorisation result: `, { authResult });<br><br>    if (!authResult) {<br>        const message = `User is not authorised to perform the ${action} action on order with id ${order.id}`;<br>        logger.error(message, { authResult: authResult, order, });<br>        throw new UnauthorizedError(message);<br>    }<br>}</pre><h4>Authorisation Requests</h4><p>With all the common logic in place, it’s time to integrate authorisation into each of the CRUD Lambda functions.</p><p>To do this, we simply call the authoriseRequest function, passing in the action type specific to the Lambda function along with the order being processed.</p><pre>...<br><br>/**<br> * Use case for creating a new order.<br> * @param newOrderDto<br> * @returns Promise&lt;OrderDto&gt;<br> */<br>export async function createOrderUseCase(<br>  newOrderDto: NewOrderDTO,<br>): Promise&lt;OrderDTO&gt; {<br>  try {<br>    const customer = await getCustomerByIDDynamoDbAdapter(<br>      newOrderDto.customerId,<br>    );<br>    const newOrder = Order.fromNewOrderDTO(newOrderDto, customer.toDTO());<br>    logger.debug(&#39;Converted newOrderDto into order&#39;, { newOrderDto, newOrder });<br>    await authoriseRequest(OrderAuthAction.CREATE_ORDER, newOrder);<br><br>    ...<br>}<br>...</pre><p>The code block above demonstrates how the authoriseRequest function is used within the createOrderUseCase function. First, the customer is retrieved, and an Order model object is constructed with the customer details. The order is then passed into authoriseRequest for validation before being saved to the database. If the user isn&#39;t authorised, an UnauthorizedError is thrown, which is handled smoothly by the Lambda middleware.</p><pre>/**<br> * Get Order use case.<br> * @param id<br> * @returns OrderDto<br> */<br>export async function getOrderUseCase(id: string): Promise&lt;OrderDTO&gt; {<br>  try {<br>    logger.debug(`Retrieving order with id &#39;${id}&#39;`);<br>    const order: Order = await getOrderByIdDynamoDbAdapter(id);<br>    await authoriseRequest(OrderAuthAction.GET_ORDER, order);<br>    logger.info(&#39;Returning Order&#39;, {order});<br>    return order.toDTO();<br>  } catch (err) {<br>    const error = err as Error;<br>    logger.error(&#39;Error occurred during order retrieval&#39;, {error});<br>    throw error;<br>  }<br>}</pre><p>The code block above showcases how the authoriseRequest function is invoked within the getOrderUseCase function. First, the order is retrieved from the database and then passed to authoriseRequest for validation. If the user lacks authorisation, an UnauthorizedError is thrown and seamlessly handled by the Lambda middleware.</p><p>You’ll notice that for GET, LIST and DELETE operations, the order is retrieved from the database before calling authoriseRequest. The same applies to CREATE and UPDATE functions, where a database operation happens before authorisation is checked.</p><p>At first glance, this might seem counterintuitive — after all, shouldn’t we verify authorisation before retrieving data? The issue is that the authorisation request requires details from the order, such as customer information, account manager, and order state. Without retrieving this data first, there’s no way to evaluate access properly.</p><p>That said, there are different ways to handle this, depending on project requirements and design preferences:</p><ol><li>Use a projection query — Instead of retrieving the entire order record, only fetch the specific attributes required for authorisation.</li><li>Implement an authorisation record — Following DynamoDB’s single table design, each order could have a separate authorisation record that contains only the attributes needed for authorisation requests.</li></ol><p>While these approaches ensure that full order records are only accessed by authorised users, they come with trade-offs. Every function invocation would now require two database queries — one to retrieve the authorisation attributes and another to fetch the full order object if access is granted.</p><p>Ultimately, the right approach depends on your project requirements, company policies, and personal preferences.</p><h3>End to End Test</h3><p>The Order Service project in the accompanying Git repository includes a Postman collection to help test the Order Service with granular authorisation in place.</p><p>The collection is organised into directories for each role and user with access to the Order Service. It contains a variety of requests — some that should be authorised and others that should be blocked, based on the user’s access level and the service’s access policy. This makes it easy to validate that authorisation rules are working as expected.</p><h3>A Future Improvement: UI-Driven Policy Management 🚀</h3><p>While the Serverless Granular Authorisation Pattern offers a robust, scalable, and cost-efficient way to manage access control — while also keeping authorisation logic separate from business logic — there’s still one limitation:</p><p>Currently, modifying authorisation policies requires teams to deploy a new version of their service through their CI/CD and change management process.</p><p>A great next step for this pattern would be to introduce a web-based UI portal that allows teams to manage authorisation policies dynamically. This portal would provide:</p><ul><li>A user-friendly interface to create and modify Cedar policies and schemas.</li><li>A backend service to persist policies to either the central policy store S3 bucket or a dedicated database.</li></ul><p>By completely decoupling policy management from service deployments, teams could make real-time authorisation updates without needing to redeploy the service — further improving maintainability, flexibility, and efficiency.</p><h3>In Conclusion</h3><p>Granular authorisation is essential for modern cloud services, and the Serverless Granular Authorisation Pattern offers a scalable, flexible, and cost-efficient solution. By leveraging Cedar, RBAC, ABAC, and context-based authorisation, teams can build secure, compliant applications without the hefty price tag.</p><p>By separating authorisation logic from business logic, this pattern makes access control easier to maintain and scale. No more hardcoded rules or manual deployments — instead, embrace a dynamic, policy-driven approach that adapts as your application grows.</p><p>If you’re frustrated with rigid access controls, now’s the time to explore granular authorisation. With the right patterns in place, access control becomes efficient, maintainable, and future-proof.</p><p>Thanks for reading 🤙🏻.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1149640f8cd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop Once, Deploy Many: An Internationalisation Software Pattern ]]></title>
            <link>https://jcdubs.medium.com/develop-once-deploy-many-an-internationalisation-software-pattern-fcca78b16802?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcca78b16802</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[internationalisation]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 14:44:36 GMT</pubDate>
            <atom:updated>2025-03-07T14:44:36.389Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWg99NyZynDaoy5zrH_mjg.jpeg" /></figure><p>In this blog post, I explore a software architecture pattern that enables teams to build a single codebase capable of handling country-specific and locale-specific configurations and business logic. This approach empowers developers to “<em>develop once, deploy many</em>,” ensuring that a single application can be customised seamlessly for different deployment regions.</p><p>In today’s global market, software projects often need to operate across different countries and regions. <strong>Internationalisation</strong> (i18n) is the process of designing and preparing applications so that they can be easily adapted to various languages, regions, and cultures without requiring engineering changes. By centralising configuration and business logic in a single codebase, teams can implement locale-specific overrides that tailor functionality to the needs of each country. This approach not only reduces duplication of effort but also enables teams to “develop once, deploy many” — building a single project that can be configured and customised at deployment time for various locales.</p><h3>Benefits of Internationalisation</h3><p>Internationalisation offers several advantages:</p><ul><li><strong>Single Codebase, Multiple Deployments:</strong> A unified project allows teams to maintain one set of core business logic and configuration files, reducing maintenance overhead.</li><li><strong>Locale-Specific Overrides:</strong> Developers can override default configurations and logic for specific countries. For instance, a default configuration applicable to all locales can be overridden by country-specific settings when needed.</li><li><strong>Faster Time-to-Market:</strong> Since the same project is used across multiple regions, adding a new locale often only requires providing localized configuration and any country-specific business rules.</li><li><strong>Consistent User Experience:</strong> By centralising core logic and only modifying locale-specific pieces, teams can ensure a consistent user experience while still accommodating local differences.</li></ul><h3>Implementing Internationalisation with TypeScript Path Aliases</h3><p>A big enabler of this internationalisation pattern is <strong>TypeScript path aliases</strong>. They make it easy to swap out configurations and logic based on the deployment region. Here’s how it works:</p><ul><li><strong>Default Files:</strong> These live in a global directory (e.g., src/global or infra/global) and contain the standard configuration and business logic that applies everywhere.</li><li><strong>Country-Specific Overrides:</strong> When deploying to a specific country, the system looks for corresponding files in a country-specific directory (e.g., src/us for the U.S., src/gb for the U.K.). If found, these files replace the defaults where needed.</li></ul><h4>Example</h4><p>Let’s say your project has a global config file at src/global/config/config.ts. By default, this is used for all deployments. But if a specific region needs a different configuration, you can add a country-specific version with the <strong>same file path</strong>, just inside the country’s directory—for example: src/gb/config/config.ts . When deploying to the UK, this override file takes precedence over the global one.</p><h4>Two Simple Rules</h4><p>To ensure this works smoothly, keep these rules in mind:</p><ol><li><strong>It only works with TypeScript module resolution</strong> — no relative file paths or manual path operations.</li><li><strong>The override file must mirror the global file’s structure and name.</strong></li></ol><ul><li>For example, you <strong>can’t</strong> override src/global/config/config.ts with something like src/uk/service-config/config.ts.</li><li>The override file <strong>must</strong> have the same name and follow the same directory structure as the original.</li></ul><p>Stick to these rules, and you’ll have a clean, scalable way to manage regional configurations in your project!</p><h3><strong>Dynamic Module Resolution via tsconfig path aliases</strong></h3><p>The tsconfig-paths package is used to dynamically configure module path aliases, making it easy to manage country-specific overrides. In tsconfig.json, the <strong>paths</strong> are set up so that when a module is imported using an alias like @src/*, the resolver first looks in a country-specific directory (determined by an environment variable like COUNTRY). If no matching file is found, it falls back to the global directory.</p><p>For example, your tsconfig.json might look like this:</p><pre>   {<br>  &quot;compilerOptions&quot;: {<br>    &quot;baseUrl&quot;: &quot;.&quot;,<br>    &quot;paths&quot;: {<br>      &quot;@src/*&quot;: [<br>        &quot;src/gb/*&quot;,<br>        &quot;src/global/*&quot;<br>      ],<br>      &quot;@infra/*&quot;: [<br>        &quot;infra/gb/*&quot;,<br>        &quot;infra/global/*&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>We use a custom script, generate-ts-config.js, to dynamically create the tsconfig.json file before deployment. This script runs before the project is built, tested, or deployed, ensuring that the path alias configuration is set based on the COUNTRY environment variable.</p><p>For example, we include generate-ts-config.js as a post-install, pre-deployment, and pre-test task in the project&#39;s package.json, so the correct tsconfig.json is generated automatically during the setup process.</p><pre>#!/usr/bin/env node<br>/* eslint-disable n/no-unpublished-require */<br>/* eslint-disable quotes */<br>/* eslint-disable prettier/prettier */<br>/* eslint-disable @typescript-eslint/no-var-requires */<br>/* eslint-disable-next-line n/shebang */<br>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>const envConfig = require(&#39;dotenv&#39;).config();<br><br>if (!envConfig.parsed.COUNTRY) {<br>  throw Error(<br>    &#39;Cannot generate dynamic paths. Please provide a COUNTRY environment variable.&#39;<br>  );<br>}<br><br>const COUNTRY = envConfig.parsed.COUNTRY;<br>const globalPath = path.join(__dirname, &#39;../src/global&#39;);<br>const srcDirs = fs.readdirSync(globalPath).filter(file =&gt; fs.lstatSync(`${globalPath}/${file}`).isDirectory());<br><br>const paths = {<br>  &#39;@infra/*&#39;: Array.from(<br>    new Set([`infra/${COUNTRY}/*`, `infra/global/*`])<br>  ),<br>}<br><br>srcDirs.forEach(dir =&gt; {<br>  paths[`@${dir}/*`] = Array.from(<br>    new Set([`src/${COUNTRY}/${dir}/*`, `src/global/${dir}/*`])<br>  )<br>  paths[`@${dir}`] = Array.from(<br>    new Set([`src/${COUNTRY}/${dir}`, `src/global/${dir}`])<br>  )<br>});<br><br>const config = {<br>  extends: &#39;./node_modules/gts/tsconfig-google.json&#39;,<br>  compilerOptions: {<br>    &quot;noImplicitAny&quot;: true,<br>    &quot;strictNullChecks&quot;: true,<br>    &quot;noImplicitThis&quot;: true,<br>    &quot;alwaysStrict&quot;: true,<br>    &quot;noUnusedLocals&quot;: false,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;noUnusedParameters&quot;: false,<br>    &quot;sourceMap&quot;: true,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;inlineSourceMap&quot;: false,<br>    &quot;inlineSources&quot;: true,<br>    &quot;experimentalDecorators&quot;: true,<br>    &quot;strictPropertyInitialization&quot;: false,<br>    &quot;typeRoots&quot;: [<br>      &quot;./node_modules/@types&quot;<br>    ],<br>    baseUrl: &#39;.&#39;,<br>    paths,<br>  },<br>  exclude: [&#39;node_modules&#39;, &#39;cdk.out&#39;],<br>};<br><br>fs.writeFileSync(<br>  path.join(__dirname, &#39;..&#39;, &#39;tsconfig.json&#39;),<br>  JSON.stringify(config, null, 4)<br>);<br><br>console.log(&#39;Created ts-config.json file&#39;);</pre><p>The generate-ts-config.js script leverages the dotenv module to load the COUNTRY environment variable, determining the deployment region. It then scans all directories within src/global and generates a tsconfig.json file with the necessary path aliases. These aliases include both the country-specific directory and a fallback to the global directory, ensuring smooth internationalization.</p><p>Additionally, the generated tsconfig.json extends gts/tsconfig-google.json, incorporating all required path mappings to support the project&#39;s structure. The final dynamically created tsconfig.json file would look like this:</p><pre>{<br>    &quot;extends&quot;: &quot;./node_modules/gts/tsconfig-google.json&quot;,<br>    &quot;compilerOptions&quot;: {<br>        &quot;noImplicitAny&quot;: true,<br>        &quot;strictNullChecks&quot;: true,<br>        &quot;noImplicitThis&quot;: true,<br>        &quot;alwaysStrict&quot;: true,<br>        &quot;noUnusedLocals&quot;: false,<br>        &quot;esModuleInterop&quot;: true,<br>        &quot;noUnusedParameters&quot;: false,<br>        &quot;sourceMap&quot;: true,<br>        &quot;resolveJsonModule&quot;: true,<br>        &quot;inlineSourceMap&quot;: false,<br>        &quot;inlineSources&quot;: true,<br>        &quot;experimentalDecorators&quot;: true,<br>        &quot;strictPropertyInitialization&quot;: false,<br>        &quot;typeRoots&quot;: [<br>            &quot;./node_modules/@types&quot;<br>        ],<br>        &quot;baseUrl&quot;: &quot;.&quot;,<br>        &quot;paths&quot;: {<br>            &quot;@infra/*&quot;: [<br>                &quot;infra/gb/*&quot;,<br>                &quot;infra/global/*&quot;<br>            ],<br>            &quot;@adapters/*&quot;: [<br>                &quot;src/gb/adapters/*&quot;,<br>                &quot;src/global/adapters/*&quot;<br>            ],<br>            &quot;@adapters&quot;: [<br>                &quot;src/gb/adapters&quot;,<br>                &quot;src/global/adapters&quot;<br>            ],<br>            &quot;@config/*&quot;: [<br>                &quot;src/gb/config/*&quot;,<br>                &quot;src/global/config/*&quot;<br>            ],<br>            &quot;@config&quot;: [<br>                &quot;src/gb/config&quot;,<br>                &quot;src/global/config&quot;<br>            ],<br>            &quot;@constants/*&quot;: [<br>                &quot;src/gb/constants/*&quot;,<br>                &quot;src/global/constants/*&quot;<br>            ],<br>            &quot;@constants&quot;: [<br>                &quot;src/gb/constants&quot;,<br>                &quot;src/global/constants&quot;<br>            ],<br>            &quot;@dto/*&quot;: [<br>                &quot;src/gb/dto/*&quot;,<br>                &quot;src/global/dto/*&quot;<br>            ],<br>            &quot;@dto&quot;: [<br>                &quot;src/gb/dto&quot;,<br>                &quot;src/global/dto&quot;<br>            ],<br>            &quot;@errors/*&quot;: [<br>                &quot;src/gb/errors/*&quot;,<br>                &quot;src/global/errors/*&quot;<br>            ],<br>            &quot;@errors&quot;: [<br>                &quot;src/gb/errors&quot;,<br>                &quot;src/global/errors&quot;<br>            ],<br>            &quot;@events/*&quot;: [<br>                &quot;src/gb/events/*&quot;,<br>                &quot;src/global/events/*&quot;<br>            ],<br>            &quot;@events&quot;: [<br>                &quot;src/gb/events&quot;,<br>                &quot;src/global/events&quot;<br>            ],<br>            &quot;@models/*&quot;: [<br>                &quot;src/gb/models/*&quot;,<br>                &quot;src/global/models/*&quot;<br>            ],<br>            &quot;@models&quot;: [<br>                &quot;src/gb/models&quot;,<br>                &quot;src/global/models&quot;<br>            ],<br>            &quot;@schemas/*&quot;: [<br>                &quot;src/gb/schemas/*&quot;,<br>                &quot;src/global/schemas/*&quot;<br>            ],<br>            &quot;@schemas&quot;: [<br>                &quot;src/gb/schemas&quot;,<br>                &quot;src/global/schemas&quot;<br>            ],<br>            &quot;@shared/*&quot;: [<br>                &quot;src/gb/shared/*&quot;,<br>                &quot;src/global/shared/*&quot;<br>            ],<br>            &quot;@shared&quot;: [<br>                &quot;src/gb/shared&quot;,<br>                &quot;src/global/shared&quot;<br>            ],<br>            &quot;@use-cases/*&quot;: [<br>                &quot;src/gb/use-cases/*&quot;,<br>                &quot;src/global/use-cases/*&quot;<br>            ],<br>            &quot;@use-cases&quot;: [<br>                &quot;src/gb/use-cases&quot;,<br>                &quot;src/global/use-cases&quot;<br>            ]<br>        }<br>    },<br>    &quot;exclude&quot;: [<br>        &quot;node_modules&quot;,<br>        &quot;cdk.out&quot;<br>    ]<br>}</pre><p>Files within a project can now be imported using the available path aliases like so:</p><pre>import {createOrderUseCase} from &#39;@use-cases/create-order-use-case&#39;;</pre><p>With the country-specific and global fallback path aliases set in tsconfig.json, we can define a default global implementation of create-order-use-case.ts in the global directory while allowing country-specific overrides in their respective directories. For example:</p><pre>src <br> |<br> | -&gt; global<br> |       | -&gt; use-cases<br> |               | -&gt; create-order-use-case.ts<br> |<br> | -&gt; gb<br> |     | -&gt; use-cases<br> |              | -&gt; create-order-use-case.ts</pre><p>If create-order-use-case.ts isn&#39;t found in the country-specific src directory, TypeScript automatically falls back to the global default version.</p><p>With this setup, deploying the service to the UK (gb) would use the UK-specific override file. However, if we deploy it to the US (us), the global default version would be used instead—since no country-specific override exists for that region.</p><h3><strong>Relative File Paths</strong></h3><p>While module imports leverage path aliases, file system operations — such as those in AWS CDK that typically use the fs or path modules—still require static, relative paths. This is especially important when specifying the handler path for a CDK Node.js Lambda L2 Construct.</p><pre>...<br><br>new njsLambda.NodejsFunction(this, serviceName, {<br>      functionName: serviceName,<br>      entry: path.resolve(<br>        __dirname,<br>        `../../../../../src/handlers/get-order.ts`,<br>      ),<br>      memorySize: 1024,<br>      runtime: lambda.Runtime.NODEJS_20_X,<br>}<br><br>...</pre><p>TypeScript path aliases — and by extension, this internationalization pattern — won’t work in this scenario.</p><p>To solve this, we use an <strong>entry file</strong> approach. For each Lambda handler, we create a static entry file that imports the actual handler using TypeScript path aliases. This ensures compatibility while maintaining flexibility. The directory structure would look like this:</p><pre>src<br> | -&gt; entry files<br> |     | -&gt; get-order.ts<br> |<br> | -&gt; global<br>       | -&gt; handlers<br>                | -&gt; get-order<br>                        | -&gt; get-order.ts</pre><p>The entry file would export the actual get-order handler like so:</p><pre>export * from &#39;@handlers/get-order&#39;;</pre><p>We would then reference the path of the entry file when providing the handler path to the CDK Lambda construct.</p><pre>...<br><br>new njsLambda.NodejsFunction(this, serviceName, {<br>      functionName: serviceName,<br>      entry: path.resolve(<br>        __dirname,<br>        `../../../../../src/entry-files/get-order.ts`,<br>      ),<br>      memorySize: 1024,<br>      runtime: lambda.Runtime.NODEJS_20_X,<br>}<br><br>...</pre><p>This workaround enables us to apply the internationalisation pattern even when working with both absolute and relative file paths.</p><h3>Demonstration: Order API with Country Specific Logic</h3><p>That’s the core idea behind the internationalisation software architecture pattern. Now, let’s see how it’s implemented in a project.</p><p><a href="https://github.com/JCDubs/Internationalisation-Architecture-Pattern">GitHub - JCDubs/Internationalisation-Architecture-Pattern</a></p><p>The example project is an <strong>Order Service API</strong> that includes customer details in the order record in both the database and API response. It follows a <strong>single-table design</strong> in DynamoDB, storing both <strong>Customer</strong> and <strong>Order</strong> data in the same table.</p><p>When an order is created, the customer data is fetched from the database and added to the order record for faster retrieval. Now, I can almost hear the collective gasps from hardcore relational database purists at the thought of duplicating data and storing it in a denormalised state 😆. I’ll cover this in a blog post in the future but for now… data in the order service API stack is stored denormalised.</p><p>Now, let’s break down how the internationalisation pattern enhances specific features in this project.</p><h4>Country Specific Models and Schema</h4><p>Different countries may require subtle variations in their models and schemas. A common example is how addresses are structured in the US versus the UK.</p><ul><li>In the <strong>US</strong>, an address typically includes state and zip code.</li><li>In the <strong>UK</strong>, these fields are referred to as county and postcode.</li></ul><p>I have decided to use state + zip code as the standard format for the default global schema.</p><p>To implement this, we would:</p><ol><li>Define the default US-based address schema in the src/global/model, src/global/dto, and src/global/schema directories.</li><li>Override these defaults with country-specific variations where needed.</li></ol><p>The global address DTO, model and schema files are shown below.</p><pre>// src/global/dto/address-dto.ts<br><br>export interface AddressDTO {<br>    addressLine1: string;<br>    addressLine2?: string;<br>    city: string;<br>    state: string;<br>    zipcode: string;<br>}</pre><pre>// src/global/models/address.ts<br><br>export interface Address {<br>    addressLine1: string;<br>    addressLine2?: string;<br>    city: string;<br>    state: string;<br>    zipcode: string;<br>}</pre><pre>// src/global/schemas/address-schema.ts<br><br>import { ADDRESS_CODE_REGEX } from &quot;@constants/regex&quot;;<br><br>const addressSchema = {<br>    type: &#39;object&#39;,<br>    properties: {<br>        addressLine1: { type: &#39;string&#39; },<br>        addressLine2: { type: &#39;string&#39; },<br>        city: { type: &#39;string&#39; },<br>        state: { type: &#39;string&#39; },<br>        zipcode: {<br>            type: &#39;string&#39;,<br>            pattern: ADDRESS_CODE_REGEX<br>        },<br>    },<br>    required: [<br>        &#39;addressLine1&#39;,<br>        &#39;city&#39;,<br>        &#39;state&#39;,<br>        &#39;zipcode&#39;,<br>    ],<br>    additionalProperties: false,<br>};<br><br>export { addressSchema };</pre><p>The address model, schema and DTO files would then be imported and used by the equivalent customer files.</p><pre>// src/global/dto/customer-dto.ts<br><br>import { AddressDTO } from &quot;@dto/address-dto&quot;;<br><br>export type CustomerDTO = {<br>  id?: string;<br>  name: string;<br>  email: string;<br>  address: AddressDTO;<br>  accountManager: string;<br>  createdDateTime?: string;<br>  updatedDateTime?: string;<br>};</pre><pre>// src/global/models/customer-types.ts<br><br>import { Address } from &#39;@models/address&#39;;<br><br>export type CustomerType = {<br>  readonly id: string;<br>  readonly name: string;<br>  readonly email: string;<br>  readonly accountManager: string;<br>  readonly address: Address;<br>  readonly createdDateTime: Date;<br>  readonly updatedDateTime: Date;<br>};</pre><pre>// src/global/schemas/customer-schema.ts<br><br>import { addressSchema } from &quot;@schemas/address-schema&quot;;<br><br>const customerSchema = {<br>  type: &#39;object&#39;,<br>  properties: {<br>    id: {type: &#39;string&#39;},<br>    name: {type: &#39;string&#39;},<br>    address: addressSchema,<br>    email: {type: &#39;string&#39;},<br>    accountManager: {type: &#39;string&#39;},<br>    createdDateTime: {type: &#39;object&#39;, format: &#39;date-time&#39;},<br>    updatedDateTime: {type: &#39;object&#39;, format: &#39;date-time&#39;},<br>  },<br>  required: [<br>    &#39;id&#39;,<br>    &#39;name&#39;,<br>    &#39;address&#39;,<br>    &#39;email&#39;,<br>    &#39;accountManager&#39;,<br>  ],<br>  additionalProperties: false,<br>};<br><br>export {customerSchema};</pre><p>With this setup, setting the COUNTRY environment variable to <strong>&quot;us&quot;</strong> or <strong>&quot;global&quot;</strong> deploys the service using the default US-based address schema.</p><p>To support the UK version of the customer address schema and service, we need to provide override files that implement the UK-specific address format, like this:</p><pre>// src/gb/dto/address-dto.ts<br><br>import {AddressDTO as orignal} from &#39;../../global/dto/address-dto&#39;;<br><br>export interface AddressDTO extends Omit&lt;orignal, &#39;state&#39; | &#39;zipcode&#39;&gt; {<br>    county: string;<br>    postcode: string;<br>}</pre><pre>// src/gb/models/address.ts<br><br>export interface Address {<br>    addressLine1: string;<br>    addressLine2?: string;<br>    city: string;<br>    county: string;<br>    postcode: string;<br>}</pre><pre>// src/gb/schemas/address-schema.ts<br><br>import { ADDRESS_CODE_REGEX } from &quot;@constants/regex&quot;;<br><br>const addressSchema = {<br>    type: &#39;object&#39;,<br>    properties: {<br>        addressLine1: { type: &#39;string&#39; },<br>        addressLine2: { type: &#39;string&#39; },<br>        city: { type: &#39;string&#39; },<br>        county: { type: &#39;string&#39; },<br>        postcode: {<br>            type: &#39;string&#39;, <br>            pattern: ADDRESS_CODE_REGEX,<br>        },<br>    },<br>    required: [<br>        &#39;addressLine1&#39;,<br>        &#39;city&#39;,<br>        &#39;county&#39;,<br>        &#39;postcode&#39;,<br>    ],<br>    additionalProperties: false,<br>};<br><br>export { addressSchema };</pre><p>By setting the COUNTRY environment variable to <strong>&quot;gb&quot;</strong> and deploying the service, we can provide a UK-specific implementation of the Order API. In this version, the address DTO, model, and schema use county and postcode instead of state and zip code.</p><p>You’ll notice that the UK versions of the address DTO and model take two different approaches to modifying the address schema:</p><ol><li><strong>Model File Approach:</strong></li></ol><ul><li>The model file defines a completely new Address interface.</li><li>It mirrors all properties from the global address schema but replaces state and zip code with county and postcode.</li></ul><p><strong>2. DTO File Approach:</strong></p><ul><li>Instead of creating a brand-new DTO, this file imports the global address DTO.</li><li>It then extends the original DTO, omits state and zip code, and adds county and postcode.</li></ul><p>Both methods work fine, but extending the default global version has a key advantage: 👉 Any updates to the original schema automatically reflect in the override, ensuring consistency with minimal maintenance.</p><h4>Country Specific Properties and Constants</h4><p>We can also apply country-specific overrides for configuration, constants, and properties.</p><p>Take the service name, for example — it would be useful if resource names reflected the country where the service is deployed. We can achieve this by using a props constants file.</p><p>The props file defines reusable string constants that are referenced throughout the codebase, improving efficiency and maintainability. Instead of hardcoding the same string value in multiple places, we define it once as a constant. If the value ever needs to change, updating it in one place ensures the change is applied everywhere it’s used.</p><p>In the Order Service API, the props file contains constants for stack names, metric parameters, and configuration properties. Suppose we want the service name — used in Lambda environment variables, log output, and metric output — to dynamically reflect the country of deployment.</p><p>To achieve this, we define a global props file like so:</p><pre>// infra/global/constants/props/props.ts<br><br>export const SERVICE = &#39;Global OrderService&#39;;<br>export const SERVICE_CODE = &#39;odr&#39;;<br>export const DOMAIN = &#39;ORDER&#39;;<br>export const AUTH = &#39;auth&#39;;<br>export const STATEFUL = &#39;stateful&#39;;<br>export const STATELESS = &#39;stateless&#39;;<br>export const METRICS_NAMESPACE_NAME = &#39;Global OrderService&#39;;</pre><p>To enable country-specific overrides for props string constants, we create country-specific props files within their respective country directories.</p><pre>// infra/gb/constants/props/props.ts<br><br>export * from &#39;../../../global/constants/props&#39;;<br>export const SERVICE = &#39;GB OrderService&#39;;<br>export const METRICS_NAMESPACE_NAME = &#39;GB OrderService&#39;;</pre><p>Of course, if we needed to support translations for countries where English isn’t the primary language, we could easily implement that as well.</p><pre>export * from &#39;../../../global/constants/props&#39;;<br>export const SERVICE = &#39;Servicio de pedidos en España&#39;;<br>export const METRICS_NAMESPACE_NAME = &#39;Servicio de pedidos en España&#39;;</pre><p>The example above is quite basic — we could dynamically construct a string that includes the country name by referencing the COUNTRY environment variable. However, the goal here is simply to demonstrate how this pattern can be applied to string constants, such as error messages, regex patterns, and more.</p><p>For instance, we could define custom error objects for validation failures and resource not found errors like this:</p><pre>// src/global/errors/validation-error/validation-error.ts<br><br>import { VALIDATION_ERROR } from &quot;@constants/errors&quot;;<br><br>export class ValidationError extends Error {<br>  constructor(message: string) {<br>    super(message);<br>    this.name = VALIDATION_ERROR;<br>  }<br>}</pre><pre>// src/global/errors/resource-not-found-error/resource-not-found-error.ts<br><br>import { RESOURCE_NOT_FOUND_ERROR } from &quot;@constants/errors&quot;;<br><br>export class ResourceNotFoundError extends Error {<br>  constructor(message: string) {<br>    super(message);<br>    this.name = RESOURCE_NOT_FOUND_ERROR;<br>  }<br>}</pre><p>You’ll notice that both errors use a string constant for the error name. These constants are defined in the global error constants file for consistency and reusability.</p><pre>// src/global/constants/errors/errors.ts<br><br>export const VALIDATION_ERROR = &#39;ValidationError&#39;;<br>export const RESOURCE_NOT_FOUND_ERROR = &#39;ResourceNotFound&#39;;</pre><p>If we need to return a different error message based on the country of deployment — or provide translations for different languages — we can achieve this using the internationalisation pattern with country-specific overrides.</p><p>For example, the code below defines error string constants in Spanish, which will be used when the Order Service is deployed to Spain:</p><pre>// src/es/constants/errors/errors.ts<br><br>export const VALIDATION_ERROR = &#39;Error de validación&#39;;<br>export const RESOURCE_NOT_FOUND_ERROR = &#39;Recurso no encontrado&#39;;</pre><p>We can apply the same approach to regular expressions.</p><p>Earlier, we looked at the address schema, where postcode and zip code validation patterns are defined using the ADDRESS_CODE_REGEX string constant from the regex constants file.</p><p>For the default implementation, we define the US zip code regex in the global directory, like this:</p><pre>// src/global/constants/regex/regex.ts<br><br>export const ADDRESS_CODE_REGEX = &#39;^\\d{5}(?:-\\d{4})?$&#39;;</pre><p>We can then use the internationalisation pattern to provide a country-specific override for the UK deployment, ensuring that customer addresses follow the correct UK postcode format.</p><pre>// src/gb/constants/regex/regex.ts<br><br>export const ADDRESS_CODE_REGEX = &#39;^(GIR ?0AA|(?:(?:[A-PR-UWYZ][0-9]{1,2}|[A-PR-UWYZ][A-HK-Y][0-9]{1,2}|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]) ?[0-9][ABD-HJLNP-UW-Z]{2}))$&#39;;</pre><p>Similarly, we can provide an override for the Spain deployment, ensuring that customer addresses adhere to the Spanish postcode format.</p><pre>// src/es/constants/regex/regex.ts<br><br>export const ADDRESS_CODE_REGEX = &#39;^\\d{5}$&#39;;</pre><h3>Conclusion</h3><p>This internationalisation pattern empowers development teams to maintain a single, robust codebase that can be tailored to meet country-specific requirements. By leveraging TypeScript path aliases and a structured override mechanism, you can ensure that core business logic and configuration remain centralised while providing flexibility to inject locale-specific differences where needed. The demonstrated Order API is just one example of how this pattern can be applied, paving the way for scalable, multi-country deployments with ease.</p><p>By “developing once” and deploying “many”, teams can focus on delivering quality features while ensuring compliance and local customisation — streamlining the path to global reach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcca78b16802" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Product Service API with Claude 3.7 Sonnet ]]></title>
            <link>https://jcdubs.medium.com/building-a-product-service-api-with-claude-3-7-sonnet-c8d22dfe7131?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8d22dfe7131</guid>
            <category><![CDATA[ai-code-generation]]></category>
            <category><![CDATA[claude-3-7-sonnet]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cline]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 10:37:08 GMT</pubDate>
            <atom:updated>2025-03-05T10:37:08.726Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDmpo049YP2RK8WP1C8drQ.jpeg" /></figure><p>Artificial intelligence is shaking up the tech world faster than ever, with tons of SaaS tools now letting anyone build apps using just plain language. These tools make it super easy for non-coders to quickly bring their ideas to life. But while they’re awesome for rapid prototyping, they sometimes miss the mark on creating scalable, maintainable, production-ready systems.</p><p>There’s a lot of talk about AI taking over IT jobs — especially programming — but instead of replacing us, AI can be a great sidekick. It handles the routine stuff, freeing up engineers to focus on creative problem-solving and high-level design.</p><p>In this blog post, I’m teaming up with AI to build a complete product service API from scratch. Using the <a href="https://code.visualstudio.com/">VS Code</a> <a href="https://cline.bot/">Cline plugin</a> along with the <a href="https://www.anthropic.com/news/claude-3-7-sonnet">Anthropic Claude 3.7 Sonnet Model</a> via Cline Bedrock, I’ll guide the model to follow top-notch cloud and software engineering practices. The project comes with solid Jest unit tests and thorough Postman end-to-end tests to ensure it’s truly enterprise-grade.</p><p>I let AI generate every part of the project while I steer the process and make sure everything meets high standards. Join me as we explore how combining human know-how with AI-driven automation can reshape the future of software development. Plus, I’ll wrap things up by comparing the total costs with what it would take for a single developer to build the same project manually.</p><h3>What is VSCode?</h3><p><a href="https://code.visualstudio.com/">Visual Studio Code</a> is a free, open-source code editor developed by Microsoft that offers a lightweight yet powerful environment for coding, debugging, and version control. With extensive extension support, it’s customisable to suit various programming languages and workflows, making it a popular choice for developers on Windows, macOS, and Linux.</p><h3>What is the Cline Plugin?</h3><p><a href="https://cline.bot/">The Cline plugin</a> is a <a href="https://code.visualstudio.com/">Visual Studio Code</a> extension that leverages AI to automate project generation and coding tasks. It integrates with models like <a href="https://www.anthropic.com/news/claude-3-7-sonnet">Anthropic’s Claude 3.7 Sonnet</a> and AWS Bedrock, enabling developers to quickly scaffold projects, generate code, and implement best practices — all through natural language prompts.</p><h3>What is Claude 3.7 Sonnet?</h3><p><a href="https://www.anthropic.com/news/claude-3-7-sonnet">Claude 3.7 Sonnet</a> is an advanced language model developed by Anthropic, renowned for its exceptional ability to generate high-quality, production-ready code. Optimised for clean, efficient outputs that adhere to industry best practices, it’s widely regarded as one of the top LLMs available for code generation today.</p><h3>VSCode Setup ⚙️</h3><p>The first step is to configure the Cline plugin in VS Code to interface with the AWS Bedrock API, which will send prompts to the Anthropic Claude 3.7 Sonnet language model. For this, we provide the AWS account credentials, specify the region as us-east-1, select to use cross-region inference and set the model as anthropic.claude-3–7-sonnet-20250219-v1:0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*TOe_aBXf5ljLkCjdvBKLSQ.png" /></figure><p>We also set the custom instructions for the model as the following, ensuring the model generates code based on industry and cloud best practices and personal preferences.</p><pre>All code should be generated with the following instructions:<br>1. Clean code with ports and adapters.<br>2. Code through interfaces.<br>3. SOLID principles.<br>4. AWS well architected best practices.<br>5. Microsoft common data model.<br>6. Should follow AWS CDK best practices when writing CDK code.<br>7. Any DynamoDB tables should be implemented with single table design.<br>8. lambda functions should be written in Node.js using the NodeJS L2 <br>   CDK construct.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*fSkX86DYa5nXPp4kEfRnxQ.png" /></figure><h3>Initial Prompt 📝</h3><p>Now that the Cline plugin is configured, it’s time to leverage Claude 3.7 Sonnet for project generation. I begin in plan mode with the following prompt in plan mode.</p><blockquote><em>“</em>Generate a Product API CDK project. The API should provide all CRUD operations, should implement the Microsoft common data model for products, include strict validation, include unit tests using jest, should use Postman and newman for end to end tests.”</blockquote><p>Cline makes the request to the Claude LLM to start planning the project resulting in the following plan. I initiate the project in plan mode to review how Claude intends to generate the project, allowing me to assess the approach before fully committing and incurring costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*itezdyfhzrcIdCeFEgTUAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*-pIohql7hOXUIxeG_ZmRFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*NE5TmYFCWFH5Esb-hUo4Jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*oUF-04QyI1lFN5_JremU1g.png" /></figure><p>The image above shows that the language model generates a comprehensive plan based on my initial instructions. The final section of the plan includes several clarifying questions aimed at refining the project’s quality. In response, I provided additional guidance to incorporate OAuth with Amazon Cognito for user authentication, and to implement CloudWatch alarms and metrics for the API and Lambda functions, all in accordance with AWS best practices and recommendations. The additional instructions were as follows:</p><blockquote>“Use Amazon Cognito to provide OAuth2 authentication and authorisation. Ensure CloudWatch alarms are created for API Gateway and AWS Lambda following AWS best practices and recommended alarms.”</blockquote><h3>Project Plan Update 📋</h3><p>With the additional instruction, Claude provides an updated project plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*D9jSDDJFIXhILgQGienEXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*yoBryrwVZUaeX7BcXzNCFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*nVPfpxeWm8SYyYk6wHpeVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*BfkEuw5g2N4oEcVxn6MchQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*hKyc33AhMRFvKoh0MZ-fLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*JJnAivqMdtqkBe5_e-GzFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*zH_IxlC4qxxa66O4thgqVw.png" /></figure><p>Claude delivers an even more refined plan for the project, complete with an architectural flow diagram and a comprehensive implementation strategy. With this blueprint in hand, the next step is to put the plan into action!</p><h3>Acting on the plan 🎭</h3><p>With the plan in place, I switched the Cline task to Act mode. This enabled the Claude model to execute the strategy and generate all project files according to the detailed implementation plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*cCspAA_oVRU_v81W3Yn4HQ.png" /></figure><p>The Claude output during project generation was as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*Pwklkh79YKxgAdwX5cuC3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*nG3P1b2iKBvfCA_rT9x6Ug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*BjisQd_HPeJ1t1N7f9kgiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*7ESIYPADNb9NtfSLS3c3HA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*BghLZE4CiId_v1PGwgQy6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*jZlKrhpQxEF2g2hnBvm77A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*9yAbOiABC3YIcH2551EouA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*U5vMSDkNUuggKkU9rK1WjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*NI2UAKYQHLV9dO0XZETu9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*jooLQpkL-gPw7xCMwgR7dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*zkCXj41MizFA3rcrXvuJhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*M5mcqEyQl4fSDrmkvy2RgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*H9Rt40VkZjZW4c0dVmCVuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*VsYU_gsFb5sEjaxk-bt85w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*QWgMpqB7Hd6PgPtgOw9zIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*nmyfnhrIRFwEBtVKYKimXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*4_PtZvEFvFN_e79cy3sXCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*PwZ8hTeDdHXY1-CdnBRXXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*KPcDzo9GncTY-0n7-xGqSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*vjtHTZTYzQP4z58-VhpCgQ.png" /></figure><p>With auto-approve enabled, the project was generated remarkably fast — taking only a few minutes, up to five at most. Claude created a complete Product API service that adheres to code and CDK best practices, producing a modular and readable codebase based on clean code principles and a ports-and-adapters architecture. Following my custom instructions, it also generated well-crafted unit tests and Postman tests using Newman, and implemented a CloudWatch dashboard, along with API and Lambda metrics and alarms aligned with AWS recommendations. The next step was to try to deploy the service to an AWS test account and manually test the service.</p><p>The Product Service API project and all code generated by Claude 3.7 sonnet can be found in the <a href="https://github.com/JCDubs/claude-product-service">GitHub Product Service repository</a>.</p><p><a href="https://github.com/JCDubs/claude-product-service">GitHub - JCDubs/claude-product-service: A Product API service completely generated using the VSCode Cline plugin and Claude 3.7 Sonnet</a></p><h3>Initial Deployment 🧨</h3><p>While inspecting the codebase, I noticed an error in one of the files where the uuid module was imported — it appeared to be the familiar issue of a missing type definition for the uuid package. This was likely due to the Cline terminal integration not working, meaning Cline couldn’t capture the results of any package installations during the act phase. I resolved this by installing the missing package.</p><p>The next issue I encountered was the absence of the cdk.json file. During project creation, Claude attempted to use the AWS CDK CLI to generate the project; however, because Cline lacked terminal access, it defaulted to manually creating all project files. I addressed this by manually adding the cdk.json file.</p><p>After reviewing all the files generated by Claude, I proceeded to deploy the service using the CDK CLI. This is when I encountered another issue: the CDK code for error alarms on the Lambda functions was failing. The alarm name was constructed using the alarm name and the lambda.functionName property. At deployment, the lambda.functionName was defined as a token rather than a string, causing the error. I fixed this by altering a Lambda reference array in the API construct. I modified it to include an object for each Lambda that provided both the lambda’s name and the lambda function itself, then updated the alarm creation logic to use the lambda name instead.</p><p>Once these issues were resolved, I successfully deployed the service to my AWS test account. My next step was to create a test user in Amazon Cognito and develop a local login script to generate an ID token for a manual Postman request to test the API. However, when I sent a create Product request, it resulted in an internal server error.</p><p>Reviewing the CloudWatch logs revealed that the Lambda runtime couldn’t find the handler function. Upon examining the API construct generated by Claude, I discovered that despite my custom instructions to create Lambda functions using the CDK L2 Node.js Lambda construct, Claude had instead used the base CDK L2 Lambda construct. To resolve this, I instructed Claude to modify the code to use the Node.js Lambda Construct along with ESBuild to bundle the TypeScript code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*N1h2YGtI1heZ4f3gWOUO7g.png" /><figcaption><a href="https://github.com/JCDubs/claude-product-service/blob/main/cline-output/4-lambda-construct-alteration.md">Change L2 construct Cline output markdown file</a></figcaption></figure><p>After deploying the change, I sent another create Product request to the API, only to encounter a new error. A review of the CloudWatch logs revealed that the aws-sdk module was missing. The issue stemmed from Claude using version 2 of the AWS SDK, which was excluded from the packaged Lambda code and unavailable in the Lambda runtime environment. To fix this, I updated the task to replace AWS SDK version 2 with version 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*N1h2YGtI1heZ4f3gWOUO7g.png" /><figcaption><a href="https://github.com/JCDubs/claude-product-service/blob/main/cline-output/5-aws-sdk-modification.md">Update AWS SDK to version 3 Cline output markdown file</a></figcaption></figure><p>With the AWS SDK updated, I redeployed the service to my AWS test account and successfully sent a create Product request to the API 🚀. After reviewing the resources, log outputs, and database entry, everything was functioning as expected. I further validated the API by executing all CRUD operations — and every request was successful! 🚀</p><h3>CloudWatch Dashboard &amp; Alarms 🚨</h3><p>Observability is an essential component of project development that many teams overlook or simply run out of time to implement due to tight deadlines. When I tasked Claude with generating a complete API, I also challenged it to deliver a CloudWatch dashboard — complete with metrics and alarms for the API and Lambda services — to achieve a truly production-ready solution. After successfully deploying and testing all API endpoints, I examined the dashboard to confirm that the recommended metrics and alarms were in place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lrxsxYqOOO2Qsb7VJC0HQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzJnfwydehCIacHRneiqaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVoqpye91-aGB0ErdMzGWA.png" /></figure><p>While I was pleased with the overall output, I noticed that the dashboard was missing alarm widgets. Although the alarms existed in CloudWatch, they weren’t centrally displayed alongside the other metrics. I then added another prompt to the task, instructing it to incorporate alarm widgets into the dashboard.</p><blockquote>“Add the CloudWatch alarms to the CloudWatch dashboard as alarm widgets.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*N1h2YGtI1heZ4f3gWOUO7g.png" /><figcaption><a href="https://github.com/JCDubs/claude-product-service/blob/main/cline-output/6-cloudwatch-dashboard-alarms-changes.md">CloudWatch Dashboard alarm widget Cline output markdown file</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDAt504xX5KsUUPxth9Ong.png" /><figcaption>A subset of the displayed alarm widgets.</figcaption></figure><p>With the alarm widgets now visible on the dashboard, I still felt something was missing: the metrics for the DynamoDB Product database were not represented, and no alarms had been implemented for DynamoDB. I added another instruction to the task to incorporate these elements into the dashboard.</p><blockquote>“Following AWS recommended guidelines, add metrics to the dashboard for the product DynamoDB table. Also create CloudWatch alarms for the Product DynamoDB table based on AWS best practice and recommendations. Add the DynamoDB product database alarms to the CloudWatch dashboard as alarm widgets.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*N1h2YGtI1heZ4f3gWOUO7g.png" /><figcaption><a href="https://github.com/JCDubs/claude-product-service/blob/main/cline-output/7-cloudwatch-dashboard-dynamo-alarms-changes.md">CloudWatch Dashboard DynamoDB changes Cline output markdown file</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T06qxemZr_--1EYy9Omp_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7SznJ7dueTXh5ZRhHZxzg.png" /></figure><p>With the Product Service API successfully deployed, it’s time to run the tests generated by the Claude language model.</p><h3>Running Unit Tests 🧪</h3><p>Claude generated all units tests and included the standard npm test task in the package.json file. Initial execution of the Jest unit tests results in one test suite failing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*U1Ez_gGjYNNUroVQOELRqQ.png" /></figure><p>Rather than manually investigating and fixing the problem with the tests, I decided to ask Claude to fix them for me with the following prompt.</p><blockquote>“I have run the unit tests and I am getting test failures in dynamodb-product-repository.ts file. the error is as follows:</blockquote><blockquote>FAIL test/unit/adapters/dynamodb-product-repository.test.ts ● Test suite failed to run lib/adapters/dynamodb-product-repository.ts:168:64 — error TS2345: Argument of type ‘{ TableName: string; Key: { PK: string; SK: string; }; UpdateExpression: string; ExpressionAttributeValues: Record&lt;string, any&gt;; ExpressionAttributeNames: Record&lt;string, string&gt;; ReturnValues: string; }’ is not assignable to parameter of type ‘UpdateCommandInput’. Type ‘{ TableName: string; Key: { PK: string; SK: string; }; UpdateExpression: string; ExpressionAttributeValues: Record&lt;string, any&gt;; ExpressionAttributeNames: Record&lt;string, string&gt;; ReturnValues: string; }’ is not assignable to type ‘Omit&lt;UpdateItemCommandInput, “Key” | “Expected” | “ExpressionAttributeValues” | “AttributeUpdates”&gt;’. Types of property ‘ReturnValues’ are incompatible. Type ‘string’ is not assignable to type ‘ReturnValue | undefined’. 168 const result = await this.docClient.send(new UpdateCommand(params)); ~~~~~~ lib/adapters/dynamodb-product-repository.ts:187:64 — error TS2345: Argument of type ‘{ TableName: string; Key: { PK: string; SK: string; }; ReturnValues: string; }’ is not assignable to parameter of type ‘DeleteCommandInput’. Type ‘{ TableName: string; Key: { PK: string; SK: string; }; ReturnValues: string; }’ is not assignable to type ‘Omit&lt;DeleteItemCommandInput, “Key” | “Expected” | “ExpressionAttributeValues”&gt;’. Types of property ‘ReturnValues’ are incompatible. Type ‘string’ is not assignable to type ‘ReturnValue | undefined’. 187 const result = await this.docClient.send(new DeleteCommand(params));”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*N1h2YGtI1heZ4f3gWOUO7g.png" /><figcaption><a href="https://github.com/JCDubs/claude-product-service/blob/main/cline-output/8-unit-test-failures.md">Unit test fix Cline output markdown file</a></figcaption></figure><p>Claude fixed the errors by making modifications to the dynamodb-product-repository-test.ts file. It’s worth noting that this task took longer to run and incurred higher API call costs because Cline couldn’t inspect the terminal output to confirm if the fixes were effective.</p><p>Another issue with the unit tests was the test branch coverage. It was coming in at 50% and failing coverage due to the threshold being set at 80%. I again asked Claude to improve branch coverage with the following prompt.</p><blockquote>“The global test coverage is not meeting the 80% threshold. Update the unit tests to provide over 80% test coverage. The report is as follows:</blockquote><blockquote>PASS test/unit/validation/product-validation.test.ts (6.564 s) — — — — — — — — | — — — — -| — — — — — | — — — — -| — — — — -| — — — — — — — — — — File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s — — — — — — — — | — — — — -| — — — — — | — — — — -| — — — — -| — — — — — — — — — — All files | 81.98 | 51.78 | 96.42 | 81.76 | adapters | 73.75 | 52.63 | 90 | 73.41 | …ository.ts | 73.75 | 52.63 | 90 | 73.41 | …63,267–273,278 core/models | 100 | 100 | 100 | 100 | product.ts | 100 | 100 | 100 | 100 | handlers | 86.88 | 40 | 100 | 86.88 | …andlers.ts | 86.88 | 40 | 100 | 86.88 | …07,235–236,263 validation | 100 | 100 | 100 | 100 | …idation.ts | 100 | 100 | 100 | 100 | — — — — — — — — | — — — — -| — — — — — | — — — — -| — — — — -| — — — — — — — — — — Jest: “global” coverage threshold for branches (80%) not met: 51.78%”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*N1h2YGtI1heZ4f3gWOUO7g.png" /><figcaption><a href="https://github.com/JCDubs/claude-product-service/blob/main/cline-output/9-unit-test-code-coverage.md">Unit test code coverage Cline output markdown file</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*TBsOPRPUxgIyI_zX3tiV9g.png" /></figure><p>Claude quickly increased test branch coverage, pushing it beyond the 80% mark.</p><h3>Postman End to End Tests 🔍</h3><p>The next phase of evaluation focused on the Postman end-to-end tests executed via Newman. Claude had already incorporated a Postman tests task into the package.json file for this purpose. Based on my previous experience with Jest unit tests, I anticipated errors during the initial run. To my surprise, all Postman tests passed on the first attempt. I only needed to populate a few values in the Postman environment file — specifically, the Product API URL and the test user’s ID Token — making the setup and execution remarkably straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*3aGfFohEhfctYaR6uBETjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*CG7HYMMUXyLz5VDawqpK6g.png" /></figure><h3>Final Project Evaluation 🤔</h3><p>At this point, the Product Service API is production-ready. With additional optimisations — such as API caching, Lambda fine-tuning, granular authorisation, and integrating email notifications with CloudWatch alarms — the generated project is scalable, modular, extensible, maintainable, and aligned with industry standards and cloud best practices. It provides a robust foundation for a production-ready service to manage an organisation’s Product Master data.</p><p>In a real-world setting with a seasoned development team, we would approach this project iteratively — developing each resource and endpoint incrementally over a series of sprints. However, the purpose of this blog post is to assess whether Cline and Claude can generate an entire production-ready project, and to evaluate how long it would take and how much it would cost.</p><h3>Improvements 🔧</h3><p>The code generated by Claude 3.7 Sonnet adheres to my specifications, delivering a modular, clean, and SOLID codebase that is extensible, maintainable, and self-documented, with robust error handling. However, if I were to restart the project from scratch, I would refine my instructions as follows:</p><ul><li>Instruct Claude to integrate Middy for middleware support across handlers.</li><li>Specify the implementation of more granular logging, including potential log sampling.</li><li>Direct the use of Lambda Power Tools for enhanced metrics, logging, and tracing, integrated through Middy middleware.</li></ul><h3>Cost Analysis 💰</h3><p>We’ve reviewed the process of generating the complete Product Service API project, but what about the cost? How long did it take for “me” (or Claude) to create it? The screenshot below displays the overall cost, along with a detailed breakdown of input and output tokens and context window usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*iNlJK2PrZ6feeJRo7FuL4w.png" /></figure><p>You can see, the project used 9.7m input tokens, 67.9 thousand output tokens, 108.9k of the 200.0k context window with an overall cost of <strong>$30.2262! </strong>Thats the total cost of API calls to AWS Bedrock using the Claude 3.7 Sonnet Large Language Model.</p><p>Another key metric is the time it took to generate and finalise the project. Remarkably, even on my first attempt using Cline and Claude to create a complete project, the entire process was completed in under two hours!</p><p>How does this compare to a scenario where a project is built entirely without AI? Let’s consider the case of a single developer creating the project from scratch. Although developer productivity varies, I’ll use my experience and some average figures to illustrate the difference.</p><p>Assume it takes one experienced developer five days to complete the entire project — setting up the project, configuring tools, provisioning infrastructure with the CDK, creating a CloudWatch dashboard with alarms, developing Lambda code for all CRUD endpoints, writing unit tests, and assembling end-to-end Postman tests. In a realistic workday of 8 hours, a developer might only spend about 5 hours actively coding.</p><p>Now, consider the cost of that developer. Using the UK average annual salary for a cloud software engineer — let’s take £60,000 as a conservative estimate — and assuming there are 252 working days in a year (8 hours each, totalling 2,016 hours), the hourly rate comes out to roughly £29.76. For a five-day project (40 hours total), the developer’s cost would be around:</p><p>£29.76/hour × 40 hours ≈ <strong>£1,190.40</strong></p><p>Now, contrast this with using AI tools. With Cline and Claude, the same project is generated in just two hours. At £29.76 per hour, two hours cost about £59.52. Adding the cost of AWS Bedrock API calls — approximately £23.62 — brings the total to roughly <strong>£83.14</strong>.</p><p>These rough calculations highlight the significant potential cost and time savings achieved by leveraging AI tools to augment software engineering tasks.</p><h3>Final Thoughts 🧐</h3><p>Using Cline and Claude 3.7 Sonnet to generate a complete Product Service API project has been interesting. The project includes unit tests, end-to-end tests, and a CloudWatch dashboard complete with metrics and alarms for all services. The detailed nature and length of this blog post reflects that the process wasn’t without challenges. I encountered minor issues with the Cline plugin’s terminal integration and some quirks in the code and tests generated by Claude.</p><p>Other than manually creating a login JavaScript script, setting up a directory for Cline output, and tweaking a naming issue in the CDK Lambda alarm resource, every piece of code and fix came directly from Claude 3.7 Sonnet.</p><p>While the cost analysis might suggest that AI can accomplish engineering tasks at a fraction of the expense of human developers, it really highlights the power of augmenting our work with AI tools.</p><p>Over the past year, AI has made significant strides. Despite the hype from venture capitalists, YouTube influencers, unicorn company executives, and AI research labs declaring the end of manual software engineering as AI models break coding benchmarks, the true potential of AI in this field will only be unlocked through the creativity, ingenuity, and insight of human engineers.</p><p>I’m immensely impressed by Claude 3.7 Sonnet’s output and look forward to using this model — and others like it — to enhance my daily workflow, boost productivity, improve quality, and accelerate the delivery of valuable solutions.</p><p>Thanks for reading! 🤙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8d22dfe7131" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Securing Sensitive Events with AWS KMS in Open Event-Driven Architectures]]></title>
            <link>https://jcdubs.medium.com/securing-sensitive-events-with-aws-kms-in-open-event-driven-architectures-ae0ffb80b30d?source=rss-9821838c8468------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae0ffb80b30d</guid>
            <category><![CDATA[aws-kms]]></category>
            <category><![CDATA[sensitive-data]]></category>
            <category><![CDATA[eda]]></category>
            <category><![CDATA[aws-iam]]></category>
            <dc:creator><![CDATA[Jason Conway-Williams]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 11:15:36 GMT</pubDate>
            <atom:updated>2025-02-26T11:15:36.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shnN3s6RWN9DOSTV5F_QjQ.jpeg" /></figure><p>In today’s fast-paced digital landscape, event-driven systems have become the backbone of many modern applications. These systems excel at decoupling services and enabling real-time data flows. However, when sensitive data is involved, an open event system — where anyone can produce or consume events — poses a significant security risk. In this blog post, we explore the challenges of handling sensitive data in an open event system and outline an architectural approach to mitigate these risks.</p><p>An effective approach is to integrate AWS Key Management Service (KMS) as the central key management solution. This method allows teams to encrypt event data at the source and ensures that only authorised consumers can access the decryption keys.</p><h3>🚨 The Open Event System Dilemma</h3><p>Imagine a scenario where any service can publish an event and any other service can subscribe to it. While this openness promotes agility and scalability, it also means that sensitive data may inadvertently be exposed. Without proper controls, unauthorised consumers can access confidential information, leading to potential breaches, regulatory violations, and loss of trust.</p><h4>Key Challenges:</h4><ul><li><strong>Unrestricted Access:</strong> In a typical open event system, all events are available to every consumer, regardless of whether they have permission to view sensitive data.</li><li><strong>Lack of Data Governance:</strong> Without mechanisms to enforce data classification and access control, sensitive payloads can be mishandled.</li><li><strong>Compliance Risks:</strong> Regulations such as GDPR and PCI-DSS require stringent controls on personal and financial data. An open event system without proper safeguards may fail to meet these requirements.</li></ul><h3>🧿 A Sensible Approach to Sensitive Data Protection</h3><p>To address these challenges, an architectural pattern can be implemented that maintains the benefits of an open event system while ensuring that only authorised parties can view and process sensitive data. The core idea is to use <strong>client-side encryption</strong> — encrypting data at the producer level — so that even if the event is consumed by an unauthorised party, the sensitive data remains protected.</p><h4>How It Works:</h4><ol><li><strong>Encryption at the Source:</strong> The service that produces the event encrypts the sensitive data using a designated encryption key. This key is managed by AWS KMS as a secure key management service.</li><li><strong>Publishing Encrypted Data in Events:</strong> The event is constructed following the event routing convention discussed in a <a href="https://medium.com/@jcdubs/unlocking-the-power-of-event-driven-architecture-with-routing-conventions-5e1e05f59421">previous blog post</a>, which includes both metaData and data root elements. The data element is encrypted using a KMS key, and the metaData object is updated with the KMS encryption key’s ARN for reference. Finally, the event is published to the central event platform.</li><li><strong>Controlled Decryption:</strong> When a consumer service retrieves the event, it must go through on time access approval process to gain access to the KMS key that would allow the consumer to decrypt the data element of the event. Only authorised services can decrypt and process the data.</li><li><strong>Audit Trail:</strong> Including key references in event metadata helps maintain an audit trail, showing which encryption key was used and when.</li></ol><h3>🔑 AWS KMS: The Heart of Secure Event Processing</h3><p>AWS KMS provides a robust and scalable solution for managing encryption keys. In an event-driven system, producers encrypt sensitive payloads using AWS KMS before publishing events to a shared event platform. This encryption means that even if an unauthorised party consumes the event, they will only see an unreadable, encrypted payload.</p><h4>Key Benefits of Using AWS KMS:</h4><ul><li><strong>Centralised Key Management:</strong> All encryption keys are managed in a single, secure AWS service, reducing the complexity of handling keys across multiple services.</li><li><strong>Scalability and Reliability:</strong> AWS KMS is designed to scale with your applications and provides high availability, ensuring your encryption keys are always accessible when needed.</li><li><strong>Integrated Auditing:</strong> AWS KMS integrates with AWS CloudTrail, providing detailed logs of key usage and access, which is essential for compliance and auditing.</li></ul><h3>📋 Requesting Access Through AWS IAM and Least Privilege</h3><p>In a secure event-driven system, it’s not enough to just encrypt the data; controlling who can decrypt it is equally important. This is where AWS Identity and Access Management (IAM) comes into play. The process is designed to ensure that access to decryption keys is granted only to teams and services that absolutely need it, following the principle of least privilege.</p><h4>How the Access Request Process Works:</h4><ol><li><strong>Encryption at the Source:</strong> The producer service encrypts sensitive event data using an encryption key managed by AWS KMS. The event metadata includes a reference to the key’s ARN (Amazon Resource Name).</li><li><strong>Event Publication:</strong> The encrypted event is published to the event bus, where it becomes accessible to all services.</li><li><strong>Access Request:</strong> When a consumer service needs to process the event, the team must first request access to the specific domain entity’s encryption key. This process involves submitting an access request, which is reviewed by the team owning the key.</li><li><strong>IAM Role Assignment:</strong> Once approved, AWS IAM is used to grant the requesting team the necessary permissions. These permissions are scoped to allow decryption of the specific event type only, adhering strictly to the principle of least privilege.</li><li><strong>Decryption and Processing:</strong> With the correct IAM role and permissions in place, the consumer service retrieves the encryption key from AWS KMS and decrypts the event data for processing.</li></ol><h3>🏛️ Architectural Overview</h3><p>Below is an architectural diagram that outlines the key components of the sensitive data protection pattern in an open event system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*jU7ob7HVcsvN8JviDGXWaw.png" /><figcaption><em>Figure 1: Architectural Flow for Secure Sensitive Data Handling in an Open Event System</em></figcaption></figure><p>In this diagram:</p><ul><li>The <strong>Producer Service</strong> encrypts the data before publishing.</li><li>The <strong>Encryption Module</strong> leverages a secure <strong>Key Management Service (KMS)</strong> to encrypt the payload.</li><li>The <strong>Central</strong> <strong>Event Platform </strong>distributes the encrypted event consisting of event metadata and encrypted data element.</li><li>The <strong>Consumer Service</strong> must request access through an <strong>Access Request &amp; Approval Process</strong> to retrieve the decryption key and process the event data. The access request is a one time process that would result in, if successful, the consumer service being added to an IAM role that would allow the service to assume the role and use the KMS key to decrypt the data.</li></ul><h3>🔍 Why This Approach Matters</h3><p>Implementing AWS KMS along with a rigorous access control process via AWS IAM delivers several critical benefits:</p><ul><li><strong>Enhanced Security:</strong> By encrypting sensitive data at the source and controlling key access, the system minimises the risk of unauthorised data exposure.</li><li><strong>Regulatory Compliance:</strong> This approach helps meet stringent data protection regulations such as GDPR and PCI-DSS by ensuring that sensitive information is only accessible by authorised entities.</li><li><strong>Operational Agility:</strong> Teams can continue to leverage the flexibility of an open event system while maintaining strict control over sensitive data, fostering innovation without sacrificing security.</li><li><strong>Auditability:</strong> Detailed logs of key usage and IAM access provide a clear audit trail, which is vital for troubleshooting and compliance audits.</li></ul><h3>⚠️ How Encryption Mitigates Risks</h3><p>This encryption-centric pattern offers several advantages:</p><ul><li><strong>Data Confidentiality:</strong> Sensitive information remains encrypted during transit and at rest. Even if unauthorised services consume the event, they cannot decipher the data.</li><li><strong>Granular Access Control:</strong> By coupling decryption with an approval process, only designated services or domains can access sensitive content.</li><li><strong>Regulatory Compliance:</strong> Encrypting sensitive data helps meet regulatory requirements such as GDPR and PCI-DSS, ensuring that data is processed lawfully and securely.</li><li><strong>Enhanced Auditability:</strong> Including the encryption key reference in event metadata creates a clear audit trail for security and compliance reviews.</li></ul><h3>📌 Conclusion</h3><p>Open event systems are powerful tools for modern application architectures, but they come with inherent security challenges — especially when sensitive data is involved. By implementing a client-side encryption pattern using AWS KMS, organisations can maintain the openness and scalability of their event systems while safeguarding confidential data. This approach not only mitigates the risks of unauthorised data access but also enhances compliance and trust in your digital ecosystem.</p><p>Integrating AWS KMS as the central key management solution and leveraging AWS IAM to enforce the principle of least privilege creates a robust framework for securing sensitive events in an open event-driven architecture. By requiring teams to request access to decryption keys before consuming events, organisations can maintain the agility of open systems while ensuring that sensitive data remains protected.</p><p>Embracing these practices not only strengthens data security but also builds trust and compliance into the very fabric of your event-driven applications.</p><p>Implementing these strategies requires thoughtful planning and coordination across development, operations, and security teams. As the landscape of data protection continues to evolve, adopting such architectural patterns becomes essential for any organisation that handles sensitive information in an open environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae0ffb80b30d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>