<?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 Kaveesh Karunarathna on Medium]]></title>
        <description><![CDATA[Stories by Kaveesh Karunarathna on Medium]]></description>
        <link>https://medium.com/@kaveeshbc?source=rss-4efa33817c52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IJ9mlMoioKa_0L_Maq7whg.jpeg</url>
            <title>Stories by Kaveesh Karunarathna on Medium</title>
            <link>https://medium.com/@kaveeshbc?source=rss-4efa33817c52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:48:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaveeshbc/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[AWS Lambda Powertools for TypeScript: Part 1 — Getting Started]]></title>
            <link>https://awstip.com/aws-lambda-powertools-for-typescript-part-1-getting-started-11256440759e?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/11256440759e</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 05:14:21 GMT</pubDate>
            <atom:updated>2026-06-16T22:34:33.465Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop reinventing the wheel. Build production-grade serverless from day one.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCweDcCajEkj9ZoinG_YPA.png" /><figcaption>AI Generated Image</figcaption></figure><p><em>This is Part 1 of a three-part series on AWS Lambda Powertools for TypeScript. Part 2 covers </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-2-observability-with-logger-tracer-and-metrics-f504691d3fc1"><em>Observability: Logger, Tracer, and Metrics in Depth</em></a><em>. Part 3 covers </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-3-advanced-patterns-c102ad34e6fe"><em>Advanced Patterns: Idempotency, Parameters, and Batch Processing</em></a><em>.</em></p><p>Every serverless developer eventually hits the same wall. Your Lambda functions work fine in isolation, but the moment you push to production, the questions start piling up: Why did that function fail silently? Why is a user seeing duplicate charges? Why are your SSM parameters hammering the network on every cold start? Why does debugging feel like reading tea leaves in CloudWatch?</p><p>These are not unique problems. They are solved problems, and <strong>AWS Lambda Powertools for TypeScript</strong> is the solution the community has converged on.</p><p>This series will take you from zero to production-confident. By the end of all three parts, you will have a complete picture of how to build observable, resilient, and operationally mature serverless applications on AWS.</p><p>Let’s start at the beginning.</p><h3>What Is AWS Lambda Powertools for TypeScript?</h3><p>AWS Lambda Powertools is an open-source developer toolkit maintained by AWS that implements best practices and utilities for Lambda functions. Originally built for Python, it was later extended to Java and, as of 2022, made generally available for <strong>TypeScript</strong>, the language most Node.js serverless developers are using today.</p><p>It is not a framework. It does not dictate how you structure your application. It is a collection of battle-tested utilities that you layer on top of your existing code:</p><ul><li><strong>Logger</strong>: structured JSON logging with correlation IDs, sampling, and Lambda context injection</li><li><strong>Tracer</strong>: AWS X-Ray tracing with zero-boilerplate subsegment and annotation support</li><li><strong>Metrics</strong>: CloudWatch custom metrics via Embedded Metrics Format (EMF)</li><li><strong>Parameters</strong>: a unified caching layer over SSM, Secrets Manager, AppConfig, and DynamoDB</li><li><strong>Idempotency</strong>: exactly-once execution guarantees backed by DynamoDB</li><li><strong>Batch Processing</strong>: partial failure handling for SQS, Kinesis, and DynamoDB Streams</li><li><strong>Event Handler</strong>: routing and validation for API Gateway, AppSync, and Lambda Function URLs</li></ul><p>Each utility is distributed as its own npm package, so you only install what you need.</p><h3>Why Should You Care?</h3><p>Before diving into code, let’s ground the “why.”</p><h3>The cold reality of serverless operations</h3><p>Lambda functions are short-lived, stateless, and invoked by events from dozens of different sources. This creates three operational challenges that most tutorials gloss over:</p><p><strong>Debugging is hard by default.</strong> console.log output is unstructured, has no correlation between invocations, and carries no context about the Lambda environment. When an incident happens at 2 AM, you need structured, searchable logs, not log spaghetti.</p><p><strong>Distributed tracing is non-trivial.</strong> A single user action might fan out across five Lambda functions, a DynamoDB table, an SQS queue, and an external API. Understanding where time is being spent, or where a failure occurred, requires proper tracing instrumentation.</p><p><strong>Re-runs cause duplicate side effects.</strong> Lambda is invoked at-least-once. SQS can re-deliver messages. API retries happen. Without idempotency controls, a payment function that gets invoked twice might charge a customer twice.</p><p>Lambda Powertools addresses all of these directly, with production-tested implementations that would take weeks to build and harden yourself.</p><h3>Project Setup</h3><h3>Prerequisites</h3><ul><li>Node.js 18+ (Lambda runtime)</li><li>AWS CDK, SAM, or Serverless Framework for deployment</li><li>An AWS account with appropriate IAM permissions</li></ul><h3>Installing the utilities</h3><p>Each utility is a separate package under the @aws-lambda-powertools scope. Install only what you need:</p><pre># Core observability trio<br>npm install \<br>  @aws-lambda-powertools/logger \<br>  @aws-lambda-powertools/tracer \<br>  @aws-lambda-powertools/metrics<br><br># Advanced utilities<br>npm install \<br>  @aws-lambda-powertools/parameters \<br>  @aws-lambda-powertools/idempotency \<br>  @aws-lambda-powertools/batch</pre><p>For the Tracer (X-Ray), you also need the AWS X-Ray SDK:</p><pre>npm install aws-xray-sdk-core</pre><h3>TypeScript configuration</h3><p>Lambda Powertools uses decorators extensively. Make sure your tsconfig.json has:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2020&quot;,<br>    &quot;module&quot;: &quot;CommonJS&quot;,<br>    &quot;lib&quot;: [&quot;ES2020&quot;],<br>    &quot;experimentalDecorators&quot;: true,<br>    &quot;emitDecoratorMetadata&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;strict&quot;: true<br>  }<br>}</pre><blockquote><strong><em>Note:</em></strong><em> If you prefer not to use decorators, every Powertools utility has a functional (non-decorator) API as well. Both styles are first-class citizens.</em></blockquote><h3>Your First Powertools-Enabled Lambda</h3><p>Here is a complete Lambda handler that uses all three observability utilities (Logger, Tracer, and Metrics) together. We will unpack each one in detail in <a href="https://claude.ai/chat/e89ef11c-acfc-431b-8dcb-a3cef5c2f24a#part-2">Part 2</a>, but seeing them work together first gives you the full picture.</p><pre>import { Logger } from &#39;@aws-lambda-powertools/logger&#39;;<br>import { Tracer } from &#39;@aws-lambda-powertools/tracer&#39;;<br>import { Metrics, MetricUnit } from &#39;@aws-lambda-powertools/metrics&#39;;<br>import type { APIGatewayProxyEvent, APIGatewayProxyResult } from &#39;aws-lambda&#39;;<br><br>// Initialize utilities at module level (outside the handler)<br>// This ensures they are shared across warm invocations<br>const logger = new Logger({<br>  serviceName: &#39;order-service&#39;,<br>  logLevel: &#39;INFO&#39;,<br>});<br>const tracer = new Tracer({<br>  serviceName: &#39;order-service&#39;,<br>});<br>const metrics = new Metrics({<br>  namespace: &#39;MyApp&#39;,<br>  serviceName: &#39;order-service&#39;,<br>});<br>export const handler = async (<br>  event: APIGatewayProxyEvent<br>): Promise&lt;APIGatewayProxyResult&gt; =&gt; {<br>  // Inject Lambda context into every log line automatically<br>  logger.addContext(context);<br>  // Add a cold-start metric automatically<br>  metrics.captureColdStartMetric();<br>  logger.info(&#39;Processing order request&#39;, {<br>    path: event.path,<br>    method: event.httpMethod,<br>  });<br>  try {<br>    const orderId = await createOrder(event);<br>    // Record a business metric<br>    metrics.addMetric(&#39;OrderCreated&#39;, MetricUnit.Count, 1);<br>    logger.info(&#39;Order created successfully&#39;, { orderId });<br>    // Flush metrics: required at the end of each invocation<br>    metrics.publishStoredMetrics();<br>    return {<br>      statusCode: 201,<br>      body: JSON.stringify({ orderId }),<br>    };<br>  } catch (error) {<br>    logger.error(&#39;Failed to create order&#39;, { error });<br>    metrics.addMetric(&#39;OrderFailed&#39;, MetricUnit.Count, 1);<br>    metrics.publishStoredMetrics();<br>    return {<br>      statusCode: 500,<br>      body: JSON.stringify({ message: &#39;Internal server error&#39; }),<br>    };<br>  }<br>};<br>async function createOrder(event: APIGatewayProxyEvent): Promise&lt;string&gt; {<br>  const segment = tracer.getSegment();<br>  const subsegment = segment?.addNewSubsegment(&#39;createOrder&#39;);<br>  try {<br>    // ... your business logic here<br>    const orderId = `ORD-${Date.now()}`;<br>    tracer.putAnnotation(&#39;orderId&#39;, orderId);<br>    return orderId;<br>  } catch (error) {<br>    subsegment?.addError(error as Error);<br>    throw error;<br>  } finally {<br>    subsegment?.close();<br>  }<br>}</pre><p>Already notice the structural improvements: every log line will carry the function name, version, cold start status, and correlation IDs automatically. Metrics are emitted as structured EMF JSON that CloudWatch understands natively. Traces link to X-Ray.</p><h3>The Decorator Pattern</h3><p>If you prefer a cleaner, declarative style, Powertools supports <strong>method decorators</strong> that wrap your handler with logging, tracing, and metric context automatically.</p><pre>import { Logger } from &#39;@aws-lambda-powertools/logger&#39;;<br>import { Tracer } from &#39;@aws-lambda-powertools/tracer&#39;;<br>import { Metrics, MetricUnit } from &#39;@aws-lambda-powertools/metrics&#39;;<br>import { LambdaInterface } from &#39;@aws-lambda-powertools/commons&#39;;<br>import type { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from &#39;aws-lambda&#39;;<br><br>const logger = new Logger({ serviceName: &#39;order-service&#39; });<br>const tracer = new Tracer({ serviceName: &#39;order-service&#39; });<br>const metrics = new Metrics({ namespace: &#39;MyApp&#39;, serviceName: &#39;order-service&#39; });<br>class OrderHandler implements LambdaInterface {<br>  @tracer.captureLambdaHandler()<br>  @logger.injectLambdaContext({ logEvent: true })<br>  @metrics.logMetrics({ captureColdStartMetric: true })<br>  public async handler(<br>    event: APIGatewayProxyEvent,<br>    context: Context<br>  ): Promise&lt;APIGatewayProxyResult&gt; {<br>    logger.info(&#39;Handling order request&#39;);<br>    metrics.addMetric(&#39;OrderAttempted&#39;, MetricUnit.Count, 1);<br>    // Your business logic here<br>    return {<br>      statusCode: 200,<br>      body: JSON.stringify({ message: &#39;OK&#39; }),<br>    };<br>  }<br>}<br>const orderHandler = new OrderHandler();<br>export const handler = orderHandler.handler.bind(orderHandler);</pre><p>The three decorators do a lot of heavy lifting:</p><ul><li>@tracer.captureLambdaHandler(): creates an X-Ray segment, captures errors, and flushes the trace automatically</li><li>@logger.injectLambdaContext(): adds function name, version, request ID, cold start flag, and (optionally) the full event to every log line</li><li>@metrics.logMetrics(): ensures metrics are flushed at the end of the invocation, even if an exception is thrown</li></ul><h3>Lambda Environment Variables</h3><p>Powertools reads sensible defaults from Lambda environment variables, reducing the amount of configuration you need to write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6h2IZTfj4FSbAwa830DDA.png" /><figcaption>AI Generated Image</figcaption></figure><p>Setting POWERTOOLS_SERVICE_NAME in your CDK or SAM template means you never have to repeat the service name in code:</p><pre>// With POWERTOOLS_SERVICE_NAME=order-service set as an env var:<br>const logger = new Logger(); // serviceName is read automatically<br>const tracer = new Tracer(); // same<br>const metrics = new Metrics({ namespace: &#39;MyApp&#39; }); // same</pre><h3>Structuring a Powertools Project</h3><p>For a real-world project, initialize all utilities in a shared module so they are instantiated once and imported wherever needed:</p><pre>src/<br>├── shared/<br>│   └── powertools.ts       # Single source of truth for all utility instances<br>├── functions/<br>│   ├── create-order/<br>│   │   └── handler.ts<br>│   └── process-payment/<br>│       └── handler.ts<br>└── types/<br>    └── orders.ts</pre><pre>// src/shared/powertools.ts<br>import { Logger } from &#39;@aws-lambda-powertools/logger&#39;;<br>import { Tracer } from &#39;@aws-lambda-powertools/tracer&#39;;<br>import { Metrics } from &#39;@aws-lambda-powertools/metrics&#39;;<br><br>export const logger = new Logger();<br>export const tracer = new Tracer();<br>export const metrics = new Metrics({ namespace: &#39;MyApp&#39; });</pre><pre>// src/functions/create-order/handler.ts<br>import { logger, tracer, metrics } from &#39;../../shared/powertools&#39;;<br>// Use them directly, no need to re-instantiate</pre><p>This pattern is particularly important for the Tracer: the X-Ray SDK is initialized once when the Lambda container starts, and re-instantiation on warm invocations can cause unexpected behavior.</p><h3>What’s Coming in Parts 2 and 3</h3><p>This first article set the stage. Here is where we go from here:</p><p><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-2-observability-with-logger-tracer-and-metrics-f504691d3fc1"><strong>Part 2: Observability — Logger, Tracer, and Metrics in Depth</strong></a></p><p>We go deep on the three observability utilities. You will learn how to correlate logs across a full request lifecycle using correlation IDs, capture custom X-Ray annotations and metadata, publish high-cardinality CloudWatch metrics using EMF, and configure log sampling to keep your CloudWatch bill under control.</p><p><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-3-advanced-patterns-c102ad34e6fe"><strong>Part 3: Advanced Patterns — Idempotency, Parameters, and Batch Processing</strong></a></p><p>We cover the utilities that protect your application’s correctness and efficiency. Idempotency prevents duplicate executions using DynamoDB. Parameters provides a caching layer over SSM and Secrets Manager that eliminates redundant API calls. Batch Processing gives you SQS partial failure handling without the boilerplate.</p><h3>Key Takeaways</h3><ul><li>AWS Lambda Powertools for TypeScript is a modular toolkit for building production-grade serverless applications</li><li>Each utility is a separate npm package, so install only what you need</li><li>Utilities are initialized once at the module level and reused across warm invocations</li><li>Both decorator and functional APIs are supported, so pick whichever fits your style</li><li>Environment variables let you configure Powertools without changing code across environments</li></ul><p><em>Continue to </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-2-observability-with-logger-tracer-and-metrics-f504691d3fc1"><em>Part 2: Observability — Logger, Tracer, and Metrics in Depth</em></a></p><p><em>Have questions or feedback? Drop a comment below or open an issue on the </em><a href="https://github.com/aws-powertools/powertools-lambda-typescript"><em>AWS Lambda Powertools GitHub repository</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11256440759e" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/aws-lambda-powertools-for-typescript-part-1-getting-started-11256440759e">AWS Lambda Powertools for TypeScript: Part 1 — Getting Started</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda Powertools for TypeScript: Part 2 — Observability with Logger, Tracer, and Metrics]]></title>
            <link>https://awstip.com/aws-lambda-powertools-for-typescript-part-2-observability-with-logger-tracer-and-metrics-f504691d3fc1?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/f504691d3fc1</guid>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 00:53:17 GMT</pubDate>
            <atom:updated>2026-06-16T22:35:14.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulJE-C5ESV0FqYc_XqMghg.png" /><figcaption>AI Generated Image</figcaption></figure><p><em>This is Part 2 of a three-part series. If you haven’t read </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-1-getting-started-11256440759e"><em>Part 1: Getting Started</em></a><em> yet, start there; it covers installation, project setup, and the foundational concepts. Part 3 covers </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-3-advanced-patterns-c102ad34e6fe"><em>Advanced Patterns: Idempotency, Parameters, and Batch Processing</em></a><em>.</em></p><p>Serverless functions are, by definition, ephemeral. They spin up, execute, and disappear, often dozens of times per second, across multiple availability zones, for the same user action. That ephemerality is what makes Lambda so powerful and so hard to debug.</p><p>The standard advice of “just add logs” is necessary but not sufficient. Logs without structure are noise. Traces without annotations are timelines without labels. Metrics without context are numbers without meaning.</p><p>This part of the series is about doing observability properly. We will go deep on three Powertools utilities (<strong>Logger</strong>, <strong>Tracer</strong>, and <strong>Metrics</strong>) and show you how they work together to give you genuine operational visibility into your serverless applications.</p><h3>The Observability Triad in Serverless</h3><p>Before the code, a quick mental model. Observability in distributed systems is typically described across three signals:</p><p><strong>Logs</strong> answer: <em>What happened?</em> They are the narrative of your application: events, errors, and state transitions, timestamped and contextualized.</p><p><strong>Traces</strong> answer: <em>Where did time go?</em> They are the timeline of a single request as it moves through your system, across functions, databases, queues, and external services.</p><p><strong>Metrics</strong> answer: <em>How is the system behaving overall?</em> They are aggregated numerical measurements over time: request rates, error rates, latency percentiles, and business KPIs.</p><p>Lambda Powertools gives you a utility for each signal, and they are designed to work together.</p><h3>Logger: Structured Logging Done Right</h3><h3>The problem with console.log</h3><pre>// ❌ What most Lambda functions look like<br>console.log(&#39;Processing order&#39;, orderId);<br>console.log(&#39;Error:&#39;, error.message);</pre><p>This output is unstructured text. CloudWatch Logs can store it, but you cannot easily filter by orderId, you cannot correlate logs across multiple functions for a single request, and you lose all Lambda context (function version, cold start status, memory limit, etc.).</p><h3>Setting up the Logger</h3><pre>import { Logger } from &#39;@aws-lambda-powertools/logger&#39;;<br><br>const logger = new Logger({<br>  serviceName: &#39;order-service&#39;,<br>  logLevel: &#39;INFO&#39;,<br>  persistentLogAttributes: {<br>    environment: process.env.STAGE ?? &#39;dev&#39;,<br>    version: process.env.npm_package_version ?? &#39;unknown&#39;,<br>  },<br>});</pre><p>Every log line this logger emits will be a structured JSON object that CloudWatch Logs Insights can query natively.</p><h3>Injecting Lambda Context</h3><p>The most important feature of the Logger is automatic Lambda context injection. Use the @logger.injectLambdaContext() decorator or call logger.addContext(context) manually:</p><pre>import type { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from &#39;aws-lambda&#39;;<br>import { LambdaInterface } from &#39;@aws-lambda-powertools/commons&#39;;<br><br>class OrderHandler implements LambdaInterface {<br>  @logger.injectLambdaContext({ logEvent: true, clearState: true })<br>  public async handler(<br>    event: APIGatewayProxyEvent,<br>    context: Context<br>  ): Promise&lt;APIGatewayProxyResult&gt; {<br>    logger.info(&#39;Order request received&#39;);<br>    // ...<br>  }<br>}</pre><p>The decorator automatically appends the following to <strong>every log line</strong> in this invocation:</p><pre>{<br>  &quot;level&quot;: &quot;INFO&quot;,<br>  &quot;message&quot;: &quot;Order request received&quot;,<br>  &quot;service&quot;: &quot;order-service&quot;,<br>  &quot;timestamp&quot;: &quot;2024-01-15T10:30:00.000Z&quot;,<br>  &quot;xray_trace_id&quot;: &quot;1-5e272176-...&quot;,<br>  &quot;cold_start&quot;: true,<br>  &quot;function_name&quot;: &quot;create-order-prod&quot;,<br>  &quot;function_memory_size&quot;: &quot;256&quot;,<br>  &quot;function_arn&quot;: &quot;arn:aws:lambda:us-east-1:...&quot;,<br>  &quot;function_request_id&quot;: &quot;d8b9f77c-...&quot;,<br>  &quot;environment&quot;: &quot;prod&quot;,<br>  &quot;version&quot;: &quot;1.4.2&quot;<br>}</pre><p>Notice cold_start: true. This is automatically set to false on subsequent warm invocations, giving you instant cold start detection in your logs without any manual tracking.</p><p>The option logEvent: true logs the incoming event (useful for debugging, but disable it in production for sensitive data). clearState: true removes any custom attributes you added during the previous invocation, preventing state bleed between warm invocations.</p><h3>Correlation IDs</h3><p>In a microservices architecture, a user request might pass through an API Gateway, three Lambda functions, and an SQS queue. Without a shared correlation ID, the logs from each hop are orphaned; you cannot connect them.</p><p>Powertools can automatically extract and propagate correlation IDs from common event sources:</p><pre>import { Logger } from &#39;@aws-lambda-powertools/logger&#39;;<br>import { CorrelationIdPaths } from &#39;@aws-lambda-powertools/logger/middleware&#39;;<br><br>const logger = new Logger({ serviceName: &#39;order-service&#39; });<br>// For API Gateway events, extract the request ID from headers<br>logger.injectLambdaContext({ correlationIdPath: CorrelationIdPaths.API_GATEWAY_REST });</pre><p>Or set a correlation ID manually when you want to propagate a business-level ID:</p><pre>logger.appendKeys({ correlationId: event.headers[&#39;x-correlation-id&#39;] ?? ulid() });<br>logger.info(&#39;Starting processing&#39;); // correlationId appears in this and every subsequent log</pre><p>When you pass the correlation ID in the headers of downstream HTTP calls or SQS message attributes, you can trace the full journey of a request across your entire system in CloudWatch Logs Insights with a single query:</p><pre>fields @timestamp, @message, service, level<br>| filter correlationId = &quot;01HJKM...&quot;<br>| sort @timestamp asc</pre><h3>Temporary and Persistent Log Attributes</h3><p>Add attributes that persist across all log lines in the invocation, or add one-time attributes to a single log call:</p><pre>// Persistent: appears on every subsequent log line in this invocation<br>logger.appendKeys({<br>  orderId: &#39;ORD-123&#39;,<br>  customerId: &#39;CUST-456&#39;,<br>});<br><br>logger.info(&#39;Validating payment method&#39;); // includes orderId and customerId<br>logger.info(&#39;Charging card&#39;);             // includes orderId and customerId<br>// One-time: appears only on this specific log line<br>logger.info(&#39;DynamoDB write complete&#39;, {<br>  tableName: &#39;Orders&#39;,<br>  itemCount: 1,<br>  consumedCapacityUnits: 0.5,<br>});</pre><h3>Log Sampling</h3><p>Debug-level logs are invaluable for diagnosing issues, but logging everything at DEBUG in production is expensive. Log sampling lets you enable DEBUG logging for a configurable fraction of invocations:</p><pre>const logger = new Logger({<br>  serviceName: &#39;order-service&#39;,<br>  logLevel: &#39;INFO&#39;,<br>  sampleRateValue: 0.05, // Enable DEBUG for 5% of invocations<br>});</pre><p>Or set it via environment variable: POWERTOOLS_LOGGER_SAMPLE_RATE=0.05.</p><p>This means 5% of your Lambda invocations will emit full DEBUG output, giving you real-world diagnostic data without the cost of logging everything.</p><h3>Child Loggers</h3><p>For large handlers with multiple logical components, create child loggers that inherit the parent’s configuration but add their own context:</p><pre>const paymentLogger = logger.createChild({<br>  persistentLogAttributes: { component: &#39;payment-processor&#39; },<br>});<br><br>paymentLogger.info(&#39;Charging customer&#39;); // Includes parent context + component</pre><h3>Tracer: Distributed Tracing with AWS X-Ray</h3><h3>Why X-Ray, and why Powertools?</h3><p>AWS X-Ray provides distributed tracing for Lambda out of the box, provided you enable active tracing on your function and instrument your code. The raw X-Ray SDK works, but it requires a lot of boilerplate: creating segments, handling errors, closing subsegments in finally blocks, and capturing service maps.</p><p>Powertools wraps all of that in a clean API.</p><h3>Setup</h3><p>Enable active tracing on your Lambda function. With CDK:</p><pre>import * as lambda from &#39;aws-cdk-lib/aws-lambda&#39;;<br>import * as lambdaNodejs from &#39;aws-cdk-lib/aws-lambda-nodejs&#39;;<br><br>const fn = new lambdaNodejs.NodejsFunction(this, &#39;CreateOrder&#39;, {<br>  tracing: lambda.Tracing.ACTIVE,<br>  // ... other config<br>});</pre><p>Or in SAM:</p><pre>Globals:<br>  Function:<br>    Tracing: Active</pre><h3>Basic Tracing</h3><pre>import { Tracer } from &#39;@aws-lambda-powertools/tracer&#39;;<br><br>const tracer = new Tracer({ serviceName: &#39;order-service&#39; });<br>class OrderHandler implements LambdaInterface {<br>  @tracer.captureLambdaHandler()<br>  public async handler(event: APIGatewayProxyEvent, context: Context) {<br>    // The decorator automatically:<br>    // - Creates a segment for the Lambda invocation<br>    // - Captures the response as trace metadata<br>    // - Captures any thrown error<br>    // - Closes the segment when the handler returns<br>    const result = await this.processOrder(event);<br>    return result;<br>  }<br>  @tracer.captureMethod()<br>  private async processOrder(event: APIGatewayProxyEvent) {<br>    // This method gets its own X-Ray subsegment automatically<br>    // The subsegment name is the method name: &quot;processOrder&quot;<br>    return { orderId: &#39;ORD-123&#39; };<br>  }<br>}</pre><h3>Custom Annotations and Metadata</h3><p>Annotations are indexed by X-Ray and are searchable via the console or AWS CLI. Use them for high-cardinality identifiers. Metadata is not indexed but can hold arbitrary objects:</p><pre>public async handler(event: APIGatewayProxyEvent, context: Context) {<br>  const orderId = event.pathParameters?.orderId;<br><br>// Annotations are searchable in X-Ray; use for filtering traces<br>  tracer.putAnnotation(&#39;orderId&#39;, orderId);<br>  tracer.putAnnotation(&#39;customerId&#39;, event.requestContext.authorizer?.claims?.sub);<br>  tracer.putAnnotation(&#39;environment&#39;, process.env.STAGE ?? &#39;dev&#39;);<br>  // Metadata can hold complex objects (not searchable but visible in trace details)<br>  tracer.putMetadata(&#39;orderPayload&#39;, JSON.parse(event.body ?? &#39;{}&#39;));<br>}<br><br>// Annotations are searchable in X-Ray; use for filtering traces<br>  tracer.putAnnotation(&#39;orderId&#39;, orderId);<br>  tracer.putAnnotation(&#39;customerId&#39;, event.requestContext.authorizer?.claims?.sub);<br>  tracer.putAnnotation(&#39;environment&#39;, process.env.STAGE ?? &#39;dev&#39;);<br>  // Metadata can hold complex objects (not searchable but visible in trace details)<br>  tracer.putMetadata(&#39;orderPayload&#39;, JSON.parse(event.body ?? &#39;{}&#39;));<br>}</pre><p>With annotations in place, you can filter traces in the X-Ray console or service map to see only traces for a specific order or customer, which is invaluable during incident triage.</p><h3>Capturing AWS SDK Calls</h3><p>Powertools can automatically wrap the AWS SDK v3 so that all DynamoDB, SQS, S3, etc. calls appear as subsegments in your traces:</p><pre>import { DynamoDBClient } from &#39;@aws-sdk/client-dynamodb&#39;;<br><br>const dynamoClient = tracer.captureAWSv3Client(new DynamoDBClient({}));<br>// Every call made via dynamoClient now appears as a trace subsegment</pre><h3>Manual Subsegments</h3><p>For cases where @tracer.captureMethod() is not flexible enough, create subsegments manually:</p><pre>public async handler(event: APIGatewayProxyEvent, context: Context) {<br>  const segment = tracer.getSegment()!;<br>  const subsegment = segment.addNewSubsegment(&#39;external-payment-api&#39;);<br><br>try {<br>    const result = await stripeClient.charge({<br>      amount: 2999,<br>      currency: &#39;usd&#39;,<br>    });<br>    tracer.putAnnotation(&#39;stripeChargeId&#39;, result.id);<br>    subsegment.addMetadata(&#39;stripeResponse&#39;, result);<br>    return result;<br>  } catch (error) {<br>    subsegment.addError(error as Error);<br>    throw error;<br>  } finally {<br>    subsegment.close(); // Always close, even on error<br>  }<br>}</pre><h3>Metrics: CloudWatch Custom Metrics via EMF</h3><h3>The CloudWatch EMF advantage</h3><p>Traditional CloudWatch metrics are published via PutMetricData API calls, one API call per metric or batch. Under high load, this adds latency and cost to your Lambda functions.</p><p>Powertools uses the <strong>CloudWatch Embedded Metrics Format (EMF)</strong>, where metrics are encoded as structured JSON in your CloudWatch Logs stream. CloudWatch parses them automatically and creates real metrics, at zero additional API call cost.</p><h3>Setting Up Metrics</h3><pre>import { Metrics, MetricUnit } from &#39;@aws-lambda-powertools/metrics&#39;;<br><br>const metrics = new Metrics({<br>  namespace: &#39;MyApp&#39;,<br>  serviceName: &#39;order-service&#39;,<br>  defaultDimensions: {<br>    environment: process.env.STAGE ?? &#39;dev&#39;,<br>    region: process.env.AWS_REGION ?? &#39;us-east-1&#39;,<br>  },<br>});</pre><h3>Recording Metrics</h3><pre>class OrderHandler implements LambdaInterface {<br>  @metrics.logMetrics({<br>    captureColdStartMetric: true,  // Automatic cold start metric<br>    defaultDimensions: { environment: process.env.STAGE ?? &#39;dev&#39; },<br>    throwOnEmptyMetrics: false,    // Don&#39;t throw if no metrics were recorded<br>  })<br>  public async handler(event: APIGatewayProxyEvent, context: Context) {<br>    metrics.addMetric(&#39;OrderAttempted&#39;, MetricUnit.Count, 1);<br><br>try {<br>      const order = await this.createOrder(event);<br>      metrics.addMetric(&#39;OrderCreated&#39;, MetricUnit.Count, 1);<br>      metrics.addMetric(&#39;OrderValue&#39;, MetricUnit.None, order.totalAmount);<br>      return { statusCode: 201, body: JSON.stringify(order) };<br>    } catch (error) {<br>      metrics.addMetric(&#39;OrderFailed&#39;, MetricUnit.Count, 1);<br>      throw error;<br>    }<br>  }<br>}</pre><p>The @metrics.logMetrics() decorator handles flushing (publishing) the metrics at the end of each invocation, including when an error is thrown. Without the decorator, you must call metrics.publishStoredMetrics() manually.</p><h3>Dimensions</h3><p>Dimensions are key-value pairs that segment your metrics. CloudWatch lets you filter and group metrics by dimension. Use them to distinguish metrics by environment, region, or any other operational attribute:</p><pre>// Add dimensions that apply to all subsequent metrics in this invocation<br>metrics.addDimension(&#39;paymentMethod&#39;, &#39;stripe&#39;);<br>metrics.addMetric(&#39;PaymentProcessed&#39;, MetricUnit.Count, 1);<br><br>// Or set high-cardinality dimensions for a single metric using a metric set<br>metrics.addMetric(&#39;LatencyMs&#39;, MetricUnit.Milliseconds, responseTime);</pre><blockquote><strong><em>Warning:</em></strong><em> CloudWatch charges per unique metric dimension combination. Don’t use high-cardinality values like user IDs or order IDs as dimensions, as that would create millions of unique dimension combinations and generate enormous costs. Use them in logs or trace annotations instead.</em></blockquote><h3>High-Resolution Metrics</h3><p>By default, CloudWatch stores metrics at 1-minute resolution. For latency-sensitive applications, you can record at 1-second resolution:</p><pre>import { Metrics, MetricUnit, MetricResolution } from &#39;@aws-lambda-powertools/metrics&#39;;<br><br>metrics.addMetric(<br>  &#39;APILatency&#39;,<br>  MetricUnit.Milliseconds,<br>  responseTimeMs,<br>  MetricResolution.High  // 1-second resolution instead of 1-minute<br>);</pre><p>High-resolution metrics cost more, so use them selectively for metrics where second-level granularity matters, typically latency and error rates for customer-facing APIs.</p><h3>Single Metric Publisher</h3><p>For cases where you need to flush a metric immediately (not at the end of the handler), use createSingleMetric:</p><pre>import { createSingleMetric } from &#39;@aws-lambda-powertools/metrics&#39;;<br><br>// Immediately flushes this metric without waiting for handler to complete<br>const singleMetric = createSingleMetric(&#39;OrderQueued&#39;, MetricUnit.Count, 1);<br>singleMetric.addDimension(&#39;queue&#39;, &#39;order-processing&#39;);</pre><h3>Bringing the Triad Together</h3><p>Here is a realistic, production-style handler that uses all three utilities together with proper error handling, correlation IDs, and business metrics:</p><pre>import { Logger } from &#39;@aws-lambda-powertools/logger&#39;;<br>import { Tracer } from &#39;@aws-lambda-powertools/tracer&#39;;<br>import { Metrics, MetricUnit } from &#39;@aws-lambda-powertools/metrics&#39;;<br>import { LambdaInterface } from &#39;@aws-lambda-powertools/commons&#39;;<br>import { DynamoDBClient } from &#39;@aws-sdk/client-dynamodb&#39;;<br>import { DynamoDBDocumentClient, PutCommand } from &#39;@aws-sdk/lib-dynamodb&#39;;<br>import type { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from &#39;aws-lambda&#39;;<br>import { randomUUID } from &#39;crypto&#39;;<br><br>const logger = new Logger({ serviceName: &#39;order-service&#39; });<br>const tracer = new Tracer({ serviceName: &#39;order-service&#39; });<br>const metrics = new Metrics({ namespace: &#39;ECommerceApp&#39;, serviceName: &#39;order-service&#39; });<br>const dynamoClient = tracer.captureAWSv3Client(<br>  DynamoDBDocumentClient.from(new DynamoDBClient({}))<br>);<br>class CreateOrderHandler implements LambdaInterface {<br>  @tracer.captureLambdaHandler()<br>  @logger.injectLambdaContext({ logEvent: false, clearState: true })<br>  @metrics.logMetrics({ captureColdStartMetric: true })<br>  public async handler(<br>    event: APIGatewayProxyEvent,<br>    context: Context<br>  ): Promise&lt;APIGatewayProxyResult&gt; {<br>    const correlationId = event.headers[&#39;x-correlation-id&#39;] ?? randomUUID();<br>    logger.appendKeys({ correlationId });<br>    tracer.putAnnotation(&#39;correlationId&#39;, correlationId);<br>    const startTime = Date.now();<br>    logger.info(&#39;Create order request received&#39;);<br>    metrics.addMetric(&#39;OrderAttempted&#39;, MetricUnit.Count, 1);<br>    try {<br>      const body = JSON.parse(event.body ?? &#39;{}&#39;);<br>      const orderId = randomUUID();<br>      logger.appendKeys({ orderId, customerId: body.customerId });<br>      tracer.putAnnotation(&#39;orderId&#39;, orderId);<br>      tracer.putAnnotation(&#39;customerId&#39;, body.customerId);<br>      await this.persistOrder({ orderId, ...body });<br>      const latencyMs = Date.now() - startTime;<br>      metrics.addMetric(&#39;OrderCreated&#39;, MetricUnit.Count, 1);<br>      metrics.addMetric(&#39;OrderCreationLatency&#39;, MetricUnit.Milliseconds, latencyMs);<br>      logger.info(&#39;Order created successfully&#39;, { latencyMs });<br>      return {<br>        statusCode: 201,<br>        headers: { &#39;x-correlation-id&#39;: correlationId },<br>        body: JSON.stringify({ orderId }),<br>      };<br>    } catch (error) {<br>      logger.error(&#39;Failed to create order&#39;, { error });<br>      metrics.addMetric(&#39;OrderCreationError&#39;, MetricUnit.Count, 1);<br>      tracer.putAnnotation(&#39;error&#39;, true);<br>      return {<br>        statusCode: 500,<br>        headers: { &#39;x-correlation-id&#39;: correlationId },<br>        body: JSON.stringify({ message: &#39;Internal server error&#39; }),<br>      };<br>    }<br>  }<br>  @tracer.captureMethod()<br>  private async persistOrder(order: Record&lt;string, unknown&gt;): Promise&lt;void&gt; {<br>    await dynamoClient.send(<br>      new PutCommand({<br>        TableName: process.env.ORDERS_TABLE!,<br>        Item: {<br>          ...order,<br>          createdAt: new Date().toISOString(),<br>          ttl: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 90, // 90-day TTL<br>        },<br>      })<br>    );<br>    logger.debug(&#39;Order persisted to DynamoDB&#39;);<br>  }<br>}<br>const handler = new CreateOrderHandler();<br>export const handler = handler.handler.bind(handler);</pre><h3>CloudWatch Logs Insights Queries</h3><p>Once your logs are structured and your metrics are flowing, you can run powerful operational queries. Here are some to bookmark:</p><p><strong>Find all errors for a specific order:</strong></p><pre>fields @timestamp, @message, level, orderId, correlationId<br>| filter level = &quot;ERROR&quot; and orderId = &quot;abc-123&quot;<br>| sort @timestamp asc</pre><p><strong>Cold start rate over time:</strong></p><pre>filter cold_start = 1<br>| stats count(*) as coldStarts by bin(5m)</pre><p><strong>P99 latency from log attributes:</strong></p><pre>filter ispresent(latencyMs)<br>| stats pct(latencyMs, 99) as p99, avg(latencyMs) as avg by bin(1m)</pre><p><strong>Error rate by service:</strong></p><pre>filter ispresent(service)<br>| stats <br>    sum(level = &quot;ERROR&quot;) as errors,<br>    count(*) as total,<br>    sum(level = &quot;ERROR&quot;) / count(*) * 100 as errorRate<br>  by service<br>| sort errorRate desc</pre><h3>Key Takeaways</h3><ul><li><strong>Logger</strong> turns your logs into structured, queryable JSON with zero boilerplate; context injection, correlation IDs, and sampling come for free</li><li><strong>Tracer</strong> wraps AWS X-Ray to give you distributed traces across Lambda, the AWS SDK, and external services with annotations that make traces searchable</li><li><strong>Metrics</strong> publishes CloudWatch custom metrics at no additional API cost via EMF, with dimension support for operational segmentation</li><li>The three utilities are designed to work together: X-Ray trace IDs appear in logs, correlation IDs appear in traces, and cold starts are tracked in metrics automatically</li></ul><p><em>← Back to </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-1-getting-started-11256440759e"><em>Part 1: Getting Started</em></a></p><p><em>Continue to </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-3-advanced-patterns-c102ad34e6fe"><em>Part 3: Advanced Patterns — Idempotency, Parameters, and Batch Processing</em></a></p><p><em>Questions about any of the examples above? Leave a comment or check the </em><a href="https://docs.powertools.aws.dev/lambda/typescript/latest/"><em>official documentation</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f504691d3fc1" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/aws-lambda-powertools-for-typescript-part-2-observability-with-logger-tracer-and-metrics-f504691d3fc1">AWS Lambda Powertools for TypeScript: Part 2 — Observability with Logger, Tracer, and Metrics</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda Powertools for TypeScript: Part 3 — Advanced Patterns]]></title>
            <link>https://awstip.com/aws-lambda-powertools-for-typescript-part-3-advanced-patterns-c102ad34e6fe?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/c102ad34e6fe</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 00:52:21 GMT</pubDate>
            <atom:updated>2026-06-16T22:36:03.136Z</atom:updated>
            <content:encoded><![CDATA[<h4>Idempotency, Parameters, and Batch Processing: the utilities that protect your application’s correctness.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6R2epBTftuLY7XV_z91Dw.png" /><figcaption>AI Generated Image</figcaption></figure><p><em>This is Part 3 of a three-part series. Part 1 covers </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-1-getting-started-11256440759e"><em>Getting Started: installation, setup, and project structure</em></a><em>. Part 2 covers </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-2-observability-with-logger-tracer-and-metrics-f504691d3fc1"><em>Observability: Logger, Tracer, and Metrics in Depth</em></a><em>. This final part focuses on the advanced utilities that handle the hard correctness problems in serverless.</em></p><p>Observability tells you <em>what happened</em>. The utilities in this article prevent the <em>wrong things</em> from happening.</p><p>In the first two parts of this series, we built a foundation of structured logging, distributed tracing, and custom metrics. Those tools are essential for understanding your system’s behavior. But there is a second class of serverless challenges that observability alone cannot solve:</p><ul><li>A payment Lambda invoked twice due to an SQS retry charges a customer twice</li><li>A Lambda reading SSM parameters on every cold start adds 300ms of latency and accumulates API costs</li><li>An SQS batch where one message fails causes all 10 messages to retry, including the nine that succeeded</li></ul><p>These are correctness and efficiency problems. Lambda Powertools has a dedicated utility for each one: <strong>Idempotency</strong>, <strong>Parameters</strong>, and <strong>Batch Processing</strong>.</p><h3>Idempotency: Exactly-Once Execution in an At-Least-Once World</h3><h3>The problem</h3><p>Lambda is invoked at-least-once. This is not a bug; it is the fundamental delivery guarantee of most AWS event sources:</p><ul><li>SQS delivers messages at least once; duplicates can occur if a message is not deleted before its visibility timeout expires</li><li>API Gateway retries on network errors</li><li>EventBridge and SNS can retry on Lambda throttles or errors</li><li>Step Functions can re-invoke a Lambda on a retry step</li></ul><p>For pure read operations, duplicate invocations are harmless. For operations with side effects (sending an email, charging a card, creating a database record), they are catastrophic.</p><p><strong>Idempotency</strong> means a function can be safely invoked multiple times with the same input and produce the same result as if it had been invoked once. Powertools gives you this guarantee backed by DynamoDB.</p><h3>How it works</h3><p>On the first invocation with a given input:</p><ol><li>Powertools hashes the payload (or a subset of it) to create an idempotency key</li><li>It writes a record to DynamoDB with status INPROGRESS and a TTL</li><li>Your function executes</li><li>The result is stored in DynamoDB with status COMPLETED</li></ol><p>On any subsequent invocation with the same input within the TTL window:</p><ul><li>Powertools detects the existing record</li><li>It returns the stored result immediately: <strong>your function body does not execute at all</strong></li><li>The caller receives the exact same response as the first invocation</li></ul><h3>Setup</h3><p>First, create a DynamoDB table for idempotency records. With CDK:</p><pre>import * as dynamodb from &#39;aws-cdk-lib/aws-dynamodb&#39;;<br><br>const idempotencyTable = new dynamodb.Table(this, &#39;IdempotencyTable&#39;, {<br>  partitionKey: { name: &#39;id&#39;, type: dynamodb.AttributeType.STRING },<br>  timeToLiveAttribute: &#39;expiration&#39;,<br>  billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,<br>  // Enable point-in-time recovery for production<br>  pointInTimeRecovery: true,<br>});<br>// Grant your Lambda function read/write access<br>idempotencyTable.grantReadWriteData(myLambdaFunction);</pre><h3>Using the makeIdempotent wrapper</h3><p>The simplest way to add idempotency is to wrap your handler with makeIdempotent:</p><pre>import { makeIdempotent } from &#39;@aws-lambda-powertools/idempotency&#39;;<br>import { DynamoDBPersistenceLayer } from &#39;@aws-lambda-powertools/idempotency/dynamodb&#39;;<br>import type { SQSEvent, Context } from &#39;aws-lambda&#39;;<br><br>const persistenceStore = new DynamoDBPersistenceLayer({<br>  tableName: process.env.IDEMPOTENCY_TABLE!,<br>});<br>const processPayment = async (event: SQSEvent): Promise&lt;void&gt; =&gt; {<br>  for (const record of event.Records) {<br>    const body = JSON.parse(record.body);<br>    await chargeCard(body.customerId, body.amount);<br>    await sendConfirmationEmail(body.customerId);<br>  }<br>};<br>// Wrap the handler; idempotency is now automatic<br>export const handler = makeIdempotent(processPayment, {<br>  persistenceStore,<br>  config: {<br>    expiresAfterSeconds: 3600, // Idempotency window: 1 hour<br>  },<br>});</pre><h3>Using the decorator</h3><p>For class-based handlers, use the @idempotent decorator:</p><pre>import { idempotent } from &#39;@aws-lambda-powertools/idempotency&#39;;<br>import { DynamoDBPersistenceLayer } from &#39;@aws-lambda-powertools/idempotency/dynamodb&#39;;<br>import { LambdaInterface } from &#39;@aws-lambda-powertools/commons&#39;;<br>import type { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from &#39;aws-lambda&#39;;<br><br>const persistenceStore = new DynamoDBPersistenceLayer({<br>  tableName: process.env.IDEMPOTENCY_TABLE!,<br>});<br>class PaymentHandler implements LambdaInterface {<br>  @idempotent({ persistenceStore })<br>  public async handler(<br>    event: APIGatewayProxyEvent,<br>    context: Context<br>  ): Promise&lt;APIGatewayProxyResult&gt; {<br>    const { customerId, amount, currency } = JSON.parse(event.body ?? &#39;{}&#39;);<br>    const chargeId = await stripeClient.charges.create({<br>      amount,<br>      currency,<br>      customer: customerId,<br>    });<br>    return {<br>      statusCode: 201,<br>      body: JSON.stringify({ chargeId: chargeId.id }),<br>    };<br>  }<br>}<br>const paymentHandler = new PaymentHandler();<br>export const handler = paymentHandler.handler.bind(paymentHandler);</pre><p>If this handler is invoked twice with the same event.body within one hour, the second invocation returns the stored chargeId from the first, so no second Stripe charge occurs.</p><h3>Customizing the idempotency key</h3><p>By default, Powertools hashes the entire event payload. For SQS, this means the full message body. You can customize which fields contribute to the key:</p><pre>const persistenceStore = new DynamoDBPersistenceLayer({<br>  tableName: process.env.IDEMPOTENCY_TABLE!,<br>});<br><br>export const handler = makeIdempotent(processOrder, {<br>  persistenceStore,<br>  config: {<br>    // Only hash these fields; ignores timestamps, request metadata, etc.<br>    eventKeyJmesPath: &#39;body.orderId&#39;,<br>    expiresAfterSeconds: 86400, // 24 hours<br>    // Validate that the payload hasn&#39;t changed for the same key<br>    payloadValidationJmesPath: &#39;body.amount&#39;,<br>  },<br>});</pre><p>The payloadValidationJmesPath option is important for financial operations: if an idempotency key is reused but with a different amount, Powertools will throw an IdempotencyValidationError rather than returning a potentially incorrect cached result.</p><h3>Idempotency for sub-functions</h3><p>You do not have to apply idempotency at the handler level. Use makeIdempotent on any inner function that has side effects:</p><pre>import { makeIdempotent } from &#39;@aws-lambda-powertools/idempotency&#39;;<br><br>const idempotentSendEmail = makeIdempotent(sendConfirmationEmail, {<br>  persistenceStore,<br>  config: {<br>    eventKeyJmesPath: &#39;customerId&#39;,<br>    expiresAfterSeconds: 3600,<br>  },<br>});<br>export const handler = async (event: SQSEvent) =&gt; {<br>  for (const record of event.Records) {<br>    const { customerId, orderId } = JSON.parse(record.body);<br>    // Even if this Lambda retries, the email is sent only once per customerId<br>    await idempotentSendEmail({ customerId, orderId });<br>  }<br>};</pre><h3>Parameters: A Caching Layer for Configuration</h3><h3>The hidden cost of configuration retrieval</h3><p>It is common to see Lambda functions fetch configuration from SSM Parameter Store or Secrets Manager on every invocation:</p><pre>// ❌ This pattern has a serious problem<br>export const handler = async (event: APIGatewayProxyEvent) =&gt; {<br>  const apiKey = await ssmClient.send(<br>    new GetParameterCommand({ Name: &#39;/myapp/third-party-api-key&#39;, WithDecryption: true })<br>  );<br>  // ...<br>};</pre><p>Every invocation makes a synchronous API call to SSM or Secrets Manager. Under load (say 500 concurrent Lambdas), this means 500 simultaneous SSM calls, each adding 50–150ms of latency to your function and counting against your SSM API rate limits.</p><p>Lambda Powertools Parameters solves this with an in-memory caching layer that fetches once and serves from cache until the TTL expires.</p><h3>SSM Parameter Store</h3><pre>import { SSMProvider } from &#39;@aws-lambda-powertools/parameters/ssm&#39;;<br><br>const ssm = new SSMProvider();<br>export const handler = async (event: APIGatewayProxyEvent) =&gt; {<br>  // Fetched from SSM on first invocation; served from cache for 5 minutes (default TTL)<br>  const apiKey = await ssm.get(&#39;/myapp/third-party-api-key&#39;, {<br>    decrypt: true,<br>    forceFetch: false, // Use cache (default)<br>  });<br>  // Fetch a SecureString parameter<br>  const dbPassword = await ssm.get(&#39;/myapp/db-password&#39;, { decrypt: true });<br>  // Fetch multiple parameters by path prefix in a single API call<br>  const appConfig = await ssm.getMultiple(&#39;/myapp/config/&#39;, {<br>    recursive: true,   // Include all parameters under this path<br>    decrypt: true,<br>    transform: &#39;json&#39;, // Auto-parse JSON parameter values<br>  });<br>  // appConfig is Record&lt;string, unknown&gt;<br>};</pre><h3>Secrets Manager</h3><pre>import { SecretsManagerProvider } from &#39;@aws-lambda-powertools/parameters/secrets&#39;;<br><br>const secrets = new SecretsManagerProvider();<br>export const handler = async (event: APIGatewayProxyEvent) =&gt; {<br>  // Fetched once, cached for 5 minutes<br>  const stripeSecret = await secrets.get(&#39;myapp/stripe-api-key&#39;);<br>  // Fetch and auto-parse a JSON secret (e.g., a database credential object)<br>  const dbCredentials = await secrets.get&lt;{ username: string; password: string }&gt;(<br>    &#39;myapp/db-credentials&#39;,<br>    { transform: &#39;json&#39; }<br>  );<br>  console.log(dbCredentials.username); // Fully typed<br>};</pre><h3>AppConfig</h3><p>For feature flags and dynamic application configuration, AppConfig provides a managed service with deployment strategies and rollback capabilities. Powertools makes it easy to consume:</p><pre>import { AppConfigProvider } from &#39;@aws-lambda-powertools/parameters/appconfig&#39;;<br><br>const appConfig = new AppConfigProvider({<br>  environment: process.env.STAGE!,<br>  application: &#39;my-ecommerce-app&#39;,<br>});<br>export const handler = async (event: APIGatewayProxyEvent) =&gt; {<br>  // Fetches configuration; cached for 5 minutes<br>  const featureFlags = await appConfig.get&lt;{<br>    newCheckoutEnabled: boolean;<br>    maxOrderValue: number;<br>  }&gt;(&#39;feature-flags&#39;, { transform: &#39;json&#39; });<br>  if (featureFlags?.newCheckoutEnabled) {<br>    return handleNewCheckout(event);<br>  }<br>  return handleLegacyCheckout(event);<br>};</pre><h3>DynamoDB Parameters</h3><p>For custom configuration patterns that don’t fit SSM or AppConfig, for example per-tenant settings stored in DynamoDB:</p><pre>import { DynamoDBProvider } from &#39;@aws-lambda-powertools/parameters/dynamodb&#39;;<br><br>const dynamoProvider = new DynamoDBProvider({<br>  tableName: process.env.CONFIG_TABLE!,<br>});<br>export const handler = async (event: APIGatewayProxyEvent) =&gt; {<br>  const tenantId = event.requestContext.authorizer?.claims?.[&#39;custom:tenantId&#39;];<br>  // Fetch config for this tenant; cached per tenantId for 5 minutes<br>  const tenantConfig = await dynamoProvider.get(tenantId);<br>};</pre><h3>Configuring the cache TTL</h3><p>The default cache TTL is 5 seconds in the provider base class, but this is configurable per provider instance or per call:</p><pre>const ssm = new SSMProvider({<br>  // Default TTL for all gets via this provider instance<br>  maxAge: 300, // 5 minutes in seconds<br>});<br><br>// Or override for a specific parameter that changes frequently<br>const volatileConfig = await ssm.get(&#39;/myapp/volatile-flag&#39;, { maxAge: 30 });<br>// Force a fresh fetch (bypass cache)<br>const freshSecret = await secrets.get(&#39;myapp/api-key&#39;, { forceFetch: true });</pre><h3>The getParameter convenience functions</h3><p>For simple single-parameter fetches, Powertools exposes convenience functions that use a shared global provider with built-in caching:</p><pre>import { getParameter, getSecret, getAppConfig } from &#39;@aws-lambda-powertools/parameters&#39;;<br><br>export const handler = async (event: APIGatewayProxyEvent) =&gt; {<br>  // These use a shared cached provider; no setup needed<br>  const apiKey = await getParameter(&#39;/myapp/api-key&#39;, { decrypt: true });<br>  const dbPassword = await getSecret(&#39;myapp/db-password&#39;);<br>};</pre><h3>Batch Processing: Partial Failure Handling for Event Sources</h3><h3>The SQS retry trap</h3><p>When Lambda processes an SQS batch, the default behavior is binary: either all messages succeed and are deleted, or the entire batch fails, and all messages return to the queue.</p><p>This creates a dangerous trap. If your batch contains 10 messages and message 7 causes an error, all 10 messages (including the 9 that processed successfully) will be re-delivered and re-processed. If messages 1 through 6 have side effects (sending emails, charging cards), those side effects execute again.</p><p>The solution is <strong>SQS partial batch responses</strong>, where you tell Lambda exactly which messages failed, and it deletes only the successful ones. Powertools wraps this in a clean, declarative API.</p><h3>SQS Batch Processing</h3><pre>import {<br>  BatchProcessor,<br>  EventType,<br>  processPartialResponse,<br>} from &#39;@aws-lambda-powertools/batch&#39;;<br>import type { SQSEvent, SQSRecord, Context } from &#39;aws-lambda&#39;;<br><br>const processor = new BatchProcessor(EventType.SQS);<br>// Your handler for a single record<br>const recordHandler = async (record: SQSRecord): Promise&lt;void&gt; =&gt; {<br>  const payload = JSON.parse(record.body);<br>  // Process this single message<br>  await sendOrderConfirmationEmail({<br>    orderId: payload.orderId,<br>    customerEmail: payload.customerEmail,<br>  });<br>  // If this throws, the message is marked as FAILED<br>  // If it returns normally, the message is marked as SUCCEEDED<br>};<br>export const handler = async (event: SQSEvent, context: Context) =&gt; {<br>  // processPartialResponse handles calling recordHandler for each message,<br>  // collecting successes and failures, and returning the correct<br>  // SQS partial batch response format<br>  return processPartialResponse(event, recordHandler, processor, {<br>    context,<br>  });<br>};</pre><p>The return value from processPartialResponse is automatically formatted as { batchItemFailures: [...] }, the structure Lambda uses to know which messages to keep in the queue. You do not build this response yourself.</p><h3>Kinesis Data Streams</h3><p>For Kinesis, the pattern is identical; just use the Kinesis event type:</p><pre>import {<br>  BatchProcessor,<br>  EventType,<br>  processPartialResponse,<br>} from &#39;@aws-lambda-powertools/batch&#39;;<br>import type { KinesisStreamEvent, KinesisStreamRecord, Context } from &#39;aws-lambda&#39;;<br><br>const processor = new BatchProcessor(EventType.KinesisDataStreams);<br>const recordHandler = async (record: KinesisStreamRecord): Promise&lt;void&gt; =&gt; {<br>  const payload = JSON.parse(<br>    Buffer.from(record.kinesis.data, &#39;base64&#39;).toString(&#39;utf-8&#39;)<br>  );<br>  await processAnalyticsEvent(payload);<br>};<br>export const handler = async (event: KinesisStreamEvent, context: Context) =&gt; {<br>  return processPartialResponse(event, recordHandler, processor, { context });<br>};</pre><h3>DynamoDB Streams</h3><pre>import {<br>  BatchProcessor,<br>  EventType,<br>  processPartialResponse,<br>} from &#39;@aws-lambda-powertools/batch&#39;;<br>import type { DynamoDBStreamEvent, DynamoDBRecord, Context } from &#39;aws-lambda&#39;;<br><br>const processor = new BatchProcessor(EventType.DynamoDBStreams);<br>const recordHandler = async (record: DynamoDBRecord): Promise&lt;void&gt; =&gt; {<br>  if (record.eventName === &#39;INSERT&#39;) {<br>    const newItem = record.dynamodb?.NewImage;<br>    await syncToSearchIndex(newItem);<br>  }<br>};<br>export const handler = async (event: DynamoDBStreamEvent, context: Context) =&gt; {<br>  return processPartialResponse(event, recordHandler, processor, { context });<br>};</pre><h3>Async vs. Sync batch processing</h3><p>By default, Powertools processes records <strong>asynchronously in parallel</strong> using Promise.all. For most use cases, this is correct and faster. But if your records must be processed in order (e.g., financial ledger entries), use the AsyncBatchProcessor with sequential processing:</p><pre>import { AsyncBatchProcessor, EventType } from &#39;@aws-lambda-powertools/batch&#39;;<br><br>// AsyncBatchProcessor processes records sequentially, in order<br>const processor = new AsyncBatchProcessor(EventType.SQS);</pre><h3>Accessing results</h3><p>After processing, you can inspect which records succeeded and which failed:</p><pre>export const handler = async (event: SQSEvent, context: Context) =&gt; {<br>  const response = await processPartialResponse(event, recordHandler, processor, {<br>    context,<br>  });<br><br>// Access per-record results for logging or metrics<br>  const { successCount, failureCount } = processor.processedBatch.reduce(<br>    (acc, result) =&gt; {<br>      if (result.status === &#39;success&#39;) acc.successCount++;<br>      else acc.failureCount++;<br>      return acc;<br>    },<br>    { successCount: 0, failureCount: 0 }<br>  );<br>  logger.info(&#39;Batch processing complete&#39;, { successCount, failureCount });<br>  metrics.addMetric(&#39;BatchSuccessCount&#39;, MetricUnit.Count, successCount);<br>  metrics.addMetric(&#39;BatchFailureCount&#39;, MetricUnit.Count, failureCount);<br>  return response;<br>};</pre><h3>Combining Batch + Idempotency</h3><p>The most powerful pattern is combining batch processing with idempotency. This gives you both partial failure handling and duplicate protection:</p><pre>import {<br>  BatchProcessor,<br>  EventType,<br>  processPartialResponse,<br>} from &#39;@aws-lambda-powertools/batch&#39;;<br>import { makeIdempotent } from &#39;@aws-lambda-powertools/idempotency&#39;;<br>import { DynamoDBPersistenceLayer } from &#39;@aws-lambda-powertools/idempotency/dynamodb&#39;;<br>import type { SQSEvent, SQSRecord, Context } from &#39;aws-lambda&#39;;<br><br>const processor = new BatchProcessor(EventType.SQS);<br>const persistenceStore = new DynamoDBPersistenceLayer({<br>  tableName: process.env.IDEMPOTENCY_TABLE!,<br>});<br>// Wrap the record handler with idempotency<br>// Key: the SQS messageId, which is naturally unique per message<br>const idempotentRecordHandler = makeIdempotent(<br>  async (record: SQSRecord): Promise&lt;void&gt; =&gt; {<br>    const payload = JSON.parse(record.body);<br>    await processOrder(payload);<br>  },<br>  {<br>    persistenceStore,<br>    config: {<br>      eventKeyJmesPath: &#39;messageId&#39;, // Use the SQS message ID as idempotency key<br>      expiresAfterSeconds: 3600,<br>    },<br>  }<br>);<br>export const handler = async (event: SQSEvent, context: Context) =&gt; {<br>  return processPartialResponse(event, idempotentRecordHandler, processor, {<br>    context,<br>  });<br>};<br></pre><p>Now your batch processing is both partially-failure-tolerant and idempotent:</p><ul><li>If a message fails, only that message returns to the queue</li><li>If the same message is re-delivered (SQS at-least-once), the idempotency layer returns the cached result without re-executing the business logic</li></ul><h3>Putting It All Together: A Production-Ready Serverless Stack</h3><p>Here is a realistic architecture that uses all six Powertools utilities together. Imagine an e-commerce order processing system:</p><pre>import { Logger } from &#39;@aws-lambda-powertools/logger&#39;;<br>import { Tracer } from &#39;@aws-lambda-powertools/tracer&#39;;<br>import { Metrics, MetricUnit } from &#39;@aws-lambda-powertools/metrics&#39;;<br>import { SSMProvider } from &#39;@aws-lambda-powertools/parameters/ssm&#39;;<br>import { SecretsManagerProvider } from &#39;@aws-lambda-powertools/parameters/secrets&#39;;<br>import { makeIdempotent } from &#39;@aws-lambda-powertools/idempotency&#39;;<br>import { DynamoDBPersistenceLayer } from &#39;@aws-lambda-powertools/idempotency/dynamodb&#39;;<br>import {<br>  BatchProcessor,<br>  EventType,<br>  processPartialResponse,<br>} from &#39;@aws-lambda-powertools/batch&#39;;<br>import { DynamoDBClient } from &#39;@aws-sdk/client-dynamodb&#39;;<br>import { DynamoDBDocumentClient } from &#39;@aws-sdk/lib-dynamodb&#39;;<br>import type { SQSEvent, SQSRecord, Context } from &#39;aws-lambda&#39;;<br><br>// ── Observability ──────────────────────────────────────────────────────────────<br>const logger = new Logger({ serviceName: &#39;order-processor&#39; });<br>const tracer = new Tracer({ serviceName: &#39;order-processor&#39; });<br>const metrics = new Metrics({ namespace: &#39;ECommerceApp&#39;, serviceName: &#39;order-processor&#39; });<br>// ── Configuration ──────────────────────────────────────────────────────────────<br>const ssm = new SSMProvider({ maxAge: 300 });<br>const secrets = new SecretsManagerProvider({ maxAge: 300 });<br>// ── AWS Clients (traced) ───────────────────────────────────────────────────────<br>const dynamoClient = tracer.captureAWSv3Client(<br>  DynamoDBDocumentClient.from(new DynamoDBClient({}))<br>);<br>// ── Idempotency ────────────────────────────────────────────────────────────────<br>const persistenceStore = new DynamoDBPersistenceLayer({<br>  tableName: process.env.IDEMPOTENCY_TABLE!,<br>});<br>// ── Batch ──────────────────────────────────────────────────────────────────────<br>const processor = new BatchProcessor(EventType.SQS);<br>// Core business logic, idempotent by message ID<br>const processOrderRecord = makeIdempotent(<br>  async (record: SQSRecord): Promise&lt;void&gt; =&gt; {<br>    const order = JSON.parse(record.body);<br>    logger.appendKeys({ orderId: order.id, customerId: order.customerId });<br>    tracer.putAnnotation(&#39;orderId&#39;, order.id);<br>    // Config is cached; no SSM call on warm invocations<br>    const [maxOrderValue, stripeKey] = await Promise.all([<br>      ssm.get&lt;number&gt;(&#39;/ecommerce/limits/max-order-value&#39;, { transform: &#39;json&#39; }),<br>      secrets.get(&#39;ecommerce/stripe-api-key&#39;),<br>    ]);<br>    if (order.totalAmount &gt; (maxOrderValue ?? 10000)) {<br>      logger.warn(&#39;Order exceeds maximum value&#39;, { totalAmount: order.totalAmount });<br>      metrics.addMetric(&#39;OrderRejectedExceedsLimit&#39;, MetricUnit.Count, 1);<br>      return;<br>    }<br>    await chargeCustomer(stripeKey!, order);<br>    await sendConfirmationEmail(order);<br>    metrics.addMetric(&#39;OrderProcessed&#39;, MetricUnit.Count, 1);<br>    metrics.addMetric(&#39;OrderValue&#39;, MetricUnit.None, order.totalAmount);<br>    logger.info(&#39;Order processed successfully&#39;);<br>  },<br>  {<br>    persistenceStore,<br>    config: {<br>      eventKeyJmesPath: &#39;messageId&#39;,<br>      expiresAfterSeconds: 86400,<br>    },<br>  }<br>);<br>// Handler<br>export const handler = async (event: SQSEvent, context: Context) =&gt; {<br>  logger.addContext(context);<br>  metrics.captureColdStartMetric();<br>  logger.info(&#39;Processing order batch&#39;, { recordCount: event.Records.length });<br>  const response = await processPartialResponse(<br>    event,<br>    processOrderRecord,<br>    processor,<br>    { context }<br>  );<br>  metrics.publishStoredMetrics();<br>  return response;<br>};</pre><p>This single Lambda function has:</p><ul><li>Structured, correlated logs with Lambda context (Logger)</li><li>Distributed traces to X-Ray with annotations (Tracer)</li><li>Business and operational metrics (Metrics)</li><li>Cached configuration and secrets with no per-invocation API overhead (Parameters)</li><li>Exactly-once order processing even on SQS retries (Idempotency)</li><li>Partial batch failure handling, so no successful orders are re-processed on retry (Batch)</li></ul><h3>IAM Permissions Summary</h3><p>Powertools utilities require IAM permissions on the Lambda execution role. Here is a quick reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Unxy-coQYA6F70LfDDN8CQ.png" /><figcaption>AI Generated Image</figcaption></figure><h3>Key Takeaways</h3><ul><li><strong>Idempotency</strong> turns your Lambda functions from at-least-once to effectively-exactly-once by storing execution results in DynamoDB and short-circuiting duplicate invocations</li><li><strong>Parameters</strong> eliminates per-invocation SSM and Secrets Manager API calls with a simple in-memory caching layer, reducing latency, cost, and the risk of hitting AWS API rate limits</li><li><strong>Batch Processing</strong> gives you partial failure handling for SQS, Kinesis, and DynamoDB Streams: failed messages return to the queue while successful ones are deleted, preventing re-processing of successful records</li><li>Combining <strong>Batch + Idempotency</strong> is the gold standard for SQS-driven Lambda functions: partial failures are handled correctly, and re-delivered messages do not cause duplicate side effects</li></ul><h3>What to Read Next</h3><p>You have now completed the full series. Here is where to go from here:</p><ul><li><a href="https://docs.powertools.aws.dev/lambda/typescript/latest/"><strong>Official Powertools documentation</strong></a>: comprehensive API reference and additional examples</li><li><a href="https://github.com/aws-powertools/powertools-lambda-typescript"><strong>Powertools GitHub repository</strong></a>: source code, open issues, and contribution guide</li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html"><strong>AWS Lambda Best Practices</strong></a>: AWS’s own guidance, which Powertools is designed around</li><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html"><strong>CloudWatch Logs Insights query syntax</strong></a>: essential for querying the structured logs your Logger now produces</li><li><a href="https://docs.aws.amazon.com/xray/latest/devguide/"><strong>AWS X-Ray documentation</strong></a>: a deep dive on trace analysis and service maps</li></ul><p><em>← Back to </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-1-getting-started-11256440759e"><em>Part 1: Getting Started</em></a></p><p><em>← Back to </em><a href="https://medium.com/@kaveeshbc/aws-lambda-powertools-for-typescript-part-2-observability-with-logger-tracer-and-metrics-f504691d3fc1"><em>Part 2: Observability — Logger, Tracer, and Metrics</em></a></p><p><em>Was this series helpful? Hit the clap button and share with your team; it makes a real difference. Questions or corrections? Drop them in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c102ad34e6fe" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/aws-lambda-powertools-for-typescript-part-3-advanced-patterns-c102ad34e6fe">AWS Lambda Powertools for TypeScript: Part 3 — Advanced Patterns</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Grade Next.js: Part 3, Performance, Security & Shipping]]></title>
            <link>https://medium.com/@kaveeshbc/building-production-grade-next-js-part-3-performance-security-shipping-6cc69401fc4c?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cc69401fc4c</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[full-stack-web-developer]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[fullstack-development]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 01:08:49 GMT</pubDate>
            <atom:updated>2026-06-16T23:31:33.637Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimization, observability, testing, and a CI/CD pipeline that holds</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vr163UaU-adtT_1Go_p-3w.png" /><figcaption>AI Generated Image</figcaption></figure><p><em>Part 3 of 3 — Design Patterns, File Structures &amp; Performance Engineering</em></p><p><em>Just joining? Start with </em><a href="https://medium.com/@kaveeshbc/building-production-grade-next-js-part-1-architecture-structure-c3b0e448d8f0"><em>Part 1 (architecture &amp; structure)</em></a><em> and </em><a href="https://medium.com/@kaveeshbc/building-production-grade-next-js-part-2-design-patterns-data-af76543beb4c"><em>Part 2 (design patterns &amp; data)</em></a><em> for the full picture.</em></p><p>You can have the cleanest architecture in the world, and it won’t matter if your app is slow, insecure, untested, or impossible to deploy confidently. This article closes those gaps.</p><h3>Performance Optimization</h3><h3>Image Optimization</h3><p>Images are the single biggest contributor to poor Largest Contentful Paint (LCP) scores. next/image handles WebP/AVIF conversion, lazy loading, and layout shift prevention, but only if you use it correctly:</p><pre>import Image from &quot;next/image&quot;;<br>// Above the fold: preload immediately<br>&lt;Image<br>  src=&quot;/hero.jpg&quot;<br>  alt=&quot;Hero banner&quot;<br>  width={1200}<br>  height={600}<br>  priority              // Removes lazy loading, preloads in &lt;head&gt;<br>  placeholder=&quot;blur&quot;<br>  blurDataURL=&quot;data:image/jpeg;base64,/9j/4AAQ...&quot; // Low-res placeholder<br>/&gt;<br>// Below the fold: let it lazy load<br>&lt;Image<br>  src={product.imageUrl}<br>  alt={product.name}<br>  width={400}<br>  height={400}<br>  sizes=&quot;(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw&quot;<br>/&gt;</pre><p>The sizes attribute is the one most developers skip, and it costs them. It tells the browser which image dimensions to download at each viewport width. Without it, the browser downloads the full-resolution image at every screen size. With it, mobile users get a 400px image instead of a 1200px one, saving 60-80% of bandwidth on the most traffic-heavy devices.</p><p>Use priority only for the LCP element, usually a hero or product image above the fold. Every other image should lazy load.</p><h3>Font Optimization</h3><p>Web fonts are a hidden source of Cumulative Layout Shift (CLS). The text renders in a fallback font, the web font loads, and the layout jumps. next/font eliminates this by self-hosting fonts and injecting size-adjust overrides that match the fallback font&#39;s metrics:</p><pre>// app/layout.tsx<br>import { DM_Sans, DM_Mono } from &quot;next/font/google&quot;;<br><br>const sans = DM_Sans({<br>  subsets: [&quot;latin&quot;],<br>  variable: &quot;--font-sans&quot;,<br>  display: &quot;swap&quot;,<br>});<br>const mono = DM_Mono({<br>  subsets: [&quot;latin&quot;],<br>  weight: [&quot;400&quot;, &quot;500&quot;],<br>  variable: &quot;--font-mono&quot;,<br>  display: &quot;swap&quot;,<br>});<br>export default function RootLayout({ children }: { children: React.ReactNode }) {<br>  return (<br>    &lt;html lang=&quot;en&quot; className={`${sans.variable} ${mono.variable}`}&gt;<br>      &lt;body className=&quot;font-sans&quot;&gt;{children}&lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>Font files are downloaded at build time and served from your own domain. No Google Fonts CDN dependency, no font-related CLS, no flash of unstyled text.</p><h3>Bundle Optimization: Dynamic Imports</h3><p>Client bundles are a liability. Every kilobyte increases parse time on low-end devices. Two rules keep bundles lean.</p><p><strong>Rule 1: Dynamically import heavy client components:</strong></p><pre>import dynamic from &quot;next/dynamic&quot;;<br><br>// Not included in the initial bundle<br>const DataTable = dynamic(() =&gt; import(&quot;@/components/data-table&quot;), {<br>  loading: () =&gt; &lt;TableSkeleton /&gt;,<br>});<br>// For browser-only libraries (no SSR needed)<br>const RichEditor = dynamic(<br>  () =&gt; import(&quot;@/components/editor&quot;).then((mod) =&gt; mod.RichEditor),<br>  {<br>    ssr: false,<br>    loading: () =&gt; &lt;EditorSkeleton /&gt;,<br>  }<br>);</pre><p><strong>Rule 2: Stop using barrel file exports:</strong></p><pre>// ❌ BAD: components/index.ts (barrel file)<br>export { Button } from &quot;./button&quot;;<br>export { Dialog } from &quot;./dialog&quot;;<br>export { DataTable } from &quot;./data-table&quot;; // 150KB — always bundled with Button</pre><pre>// ✅ GOOD: Import directly from the module<br>import { Button } from &quot;@/components/ui/button&quot;;<br>import { Dialog } from &quot;@/components/ui/dialog&quot;;</pre><p>Barrel files defeat tree-shaking. When you import Button from a barrel that re-exports twenty components, bundlers often include all twenty in the output. Import directly from the source file.</p><h3>Parallel Data Fetching</h3><p>The most common performance mistake in Server Components: sequential awaits.</p><pre>// ❌ BAD — Sequential fetches: 300ms + 300ms + 300ms = ~900ms<br>export default async function Dashboard() {<br>  const user = await getUser();<br>  const orders = await getOrders();<br>  const stats = await getStats();<br>}</pre><pre>// ✅ GOOD — Parallel fetches: max(300ms, 300ms, 300ms) = ~300ms<br>export default async function Dashboard() {<br>  const [user, orders, stats] = await Promise.all([<br>    getUser(),<br>    getOrders(),<br>    getStats(),<br>  ]);<br>}</pre><p>When some requests depend on earlier results, use Promise.all for the independent branches:</p><pre>const user = await getUser(); // Required first<br><br>// These both depend on user.id but not on each other<br>const [orders, permissions] = await Promise.all([<br>  getOrdersByUser(user.id),<br>  getPermissions(user.roleId),<br>]);</pre><h3>Streaming with Suspense</h3><p>Don’t block the entire page on slow data. Wrap slow Server Components in Suspense and stream them in as their data resolves:</p><pre>// app/dashboard/page.tsx<br>import { Suspense } from &quot;react&quot;;<br>import { UserGreeting } from &quot;./user-greeting&quot;;       // Fast, renders immediately<br>import { RecentOrders } from &quot;./recent-orders&quot;;       // Slow DB join<br>import { AnalyticsWidget } from &quot;./analytics-widget&quot;; // Slow external API call<br>import { Skeleton } from &quot;@/components/ui/skeleton&quot;;<br><br>export default function DashboardPage() {<br>  return (<br>    &lt;div&gt;<br>      {/* Renders immediately, no Suspense needed */}<br>      &lt;UserGreeting /&gt;<br>      {/* Streamed in as the DB query resolves */}<br>      &lt;Suspense fallback={&lt;Skeleton className=&quot;h-64 w-full&quot; /&gt;}&gt;<br>        &lt;RecentOrders /&gt;<br>      &lt;/Suspense&gt;<br>      {/* Streamed in independently, doesn&#39;t wait for RecentOrders */}<br>      &lt;Suspense fallback={&lt;Skeleton className=&quot;h-32 w-full&quot; /&gt;}&gt;<br>        &lt;AnalyticsWidget /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The HTML shell with UserGreeting reaches the browser almost instantly. The skeletons render. As RecentOrders and AnalyticsWidget resolve on the server, their HTML is streamed into the page. The user sees progressive content rather than a blank screen or a full-page spinner, and your TTFB drops accordingly.</p><h3>Middleware and Authentication</h3><h3>Edge Middleware for Route Guards</h3><p>Middleware runs at the edge before the request reaches your server, making it the right place for authentication guards, redirects, and feature flags:</p><pre>// middleware.ts<br>import { NextResponse } from &quot;next/server&quot;;<br>import type { NextRequest } from &quot;next/server&quot;;<br>import { getToken } from &quot;next-auth/jwt&quot;;<br><br>const PUBLIC_ROUTES = [&quot;/&quot;, &quot;/login&quot;, &quot;/signup&quot;, &quot;/blog&quot;];<br>const AUTH_ROUTES = [&quot;/login&quot;, &quot;/signup&quot;];<br>export async function middleware(req: NextRequest) {<br>  const { pathname } = req.nextUrl;<br>  const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });<br>  const isPublic = PUBLIC_ROUTES.some((r) =&gt; pathname.startsWith(r));<br>  const isAuthRoute = AUTH_ROUTES.some((r) =&gt; pathname.startsWith(r));<br>  // Authenticated users shouldn&#39;t see login/signup<br>  if (token &amp;&amp; isAuthRoute) {<br>    return NextResponse.redirect(new URL(&quot;/dashboard&quot;, req.url));<br>  }<br>  // Unauthenticated users get redirected with a callbackUrl<br>  if (!token &amp;&amp; !isPublic) {<br>    const loginUrl = new URL(&quot;/login&quot;, req.url);<br>    loginUrl.searchParams.set(&quot;callbackUrl&quot;, pathname);<br>    return NextResponse.redirect(loginUrl);<br>  }<br>  return NextResponse.next();<br>}<br>export const config = {<br>  // Match everything except Next.js internals and static files<br>  matcher: [&quot;/((?!api|_next/static|_next/image|favicon.ico).*)&quot;],<br>};</pre><p>The matcher pattern is critical. Without it, middleware runs on every _next/static asset request, adding latency for no benefit.</p><h3>Security Headers</h3><pre>// next.config.ts<br>const securityHeaders = [<br>  { key: &quot;X-DNS-Prefetch-Control&quot;, value: &quot;on&quot; },<br>  { key: &quot;X-Frame-Options&quot;, value: &quot;SAMEORIGIN&quot; },<br>  { key: &quot;X-Content-Type-Options&quot;, value: &quot;nosniff&quot; },<br>  { key: &quot;Referrer-Policy&quot;, value: &quot;strict-origin-when-cross-origin&quot; },<br>  { key: &quot;Permissions-Policy&quot;, value: &quot;camera=(), microphone=(), geolocation=()&quot; },<br>  {<br>    key: &quot;Strict-Transport-Security&quot;,<br>    value: &quot;max-age=63072000; includeSubDomains; preload&quot;,<br>  },<br>  {<br>    key: &quot;Content-Security-Policy&quot;,<br>    value: [<br>      &quot;default-src &#39;self&#39;&quot;,<br>      &quot;script-src &#39;self&#39; &#39;unsafe-eval&#39; &#39;unsafe-inline&#39;&quot;,<br>      &quot;style-src &#39;self&#39; &#39;unsafe-inline&#39;&quot;,<br>      &quot;img-src &#39;self&#39; data: https:&quot;,<br>      &quot;font-src &#39;self&#39;&quot;,<br>      &quot;connect-src &#39;self&#39; https://api.stripe.com&quot;,<br>    ].join(&quot;; &quot;),<br>  },<br>];<br><br>export default {<br>  async headers() {<br>    return [{ source: &quot;/(.*)&quot;, headers: securityHeaders }];<br>  },<br>};</pre><p>Run your deployed app through <a href="https://securityheaders.com/">securityheaders.com</a> and <a href="https://observatory.mozilla.org/">Mozilla Observatory</a> after setup. Both give you a letter grade and specific recommendations.</p><h3>Error Handling</h3><h3>File-Based Error Boundaries</h3><p>Next.js supports error boundaries at the file system level. error.tsx files catch errors in their segment and everything below it:</p><pre>app/<br>├── error.tsx              catches root-level errors<br>├── (dashboard)/<br>│   ├── error.tsx          catches only dashboard errors<br>│   └── analytics/<br>│       └── error.tsx      catches only analytics errors</pre><pre>// app/(dashboard)/error.tsx<br>&quot;use client&quot;; // Error boundaries must be Client Components<br><br>import { useEffect } from &quot;react&quot;;<br>import { Button } from &quot;@/components/ui/button&quot;;<br>export default function DashboardError({<br>  error,<br>  reset,<br>}: {<br>  error: Error &amp; { digest?: string };<br>  reset: () =&gt; void;<br>}) {<br>  useEffect(() =&gt; {<br>    reportError(error); // Report to Sentry, Datadog, etc.<br>  }, [error]);<br>  return (<br>    &lt;div className=&quot;flex flex-col items-center gap-4 p-8 text-center&quot;&gt;<br>      &lt;h2 className=&quot;text-xl font-semibold&quot;&gt;Something went wrong&lt;/h2&gt;<br>      &lt;p className=&quot;text-muted-foreground text-sm max-w-md&quot;&gt;{error.message}&lt;/p&gt;<br>      &lt;Button onClick={reset} variant=&quot;outline&quot;&gt;<br>        Try again<br>      &lt;/Button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The digest field is a server-side error hash that maps to your server logs. It&#39;s safe to expose to the client for support tickets without leaking implementation details.</p><h3>Observability and Monitoring</h3><h3>OpenTelemetry Integration</h3><p>Next.js 14+ has first-class OpenTelemetry support via the instrumentation file:</p><pre>// instrumentation.ts<br>export async function register() {<br>  if (process.env.NEXT_RUNTIME === &quot;nodejs&quot;) {<br>    const { NodeSDK } = await import(&quot;@opentelemetry/sdk-node&quot;);<br>    const { getNodeAutoInstrumentations } = await import(<br>      &quot;@opentelemetry/auto-instrumentations-node&quot;<br>    );<br>    const { OTLPTraceExporter } = await import(<br>      &quot;@opentelemetry/exporter-trace-otlp-http&quot;<br>    );<br>    const sdk = new NodeSDK({<br>          traceExporter: new OTLPTraceExporter({<br>            url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,<br>          }),<br>          instrumentations: [getNodeAutoInstrumentations()],<br>        });<br>        sdk.start();<br>      }<br>}</pre><p>This gives you automatic traces for every incoming request, database query, and outgoing HTTP call, routed to Jaeger, Honeycomb, Datadog, or any OTLP-compatible backend.</p><h3>Structured Logging</h3><p>console.log in production is unstructured, unsearchable, and context-free. Use structured logging from day one:</p><pre>// lib/logger.ts<br>import pino from &quot;pino&quot;;<br><br>export const logger = pino({<br>  level: process.env.NODE_ENV === &quot;production&quot; ? &quot;info&quot; : &quot;debug&quot;,<br>  ...(process.env.NODE_ENV !== &quot;production&quot; &amp;&amp; {<br>    transport: { target: &quot;pino-pretty&quot;, options: { colorize: true } },<br>  }),<br>});</pre><p>Every log call carries structured context:</p><pre>logger.info({ userId, orderId, amount }, &quot;Order created&quot;);<br>logger.error({ err, userId, orderId }, &quot;Payment failed&quot;);<br>logger.warn({ userId, plan: &quot;free&quot;, limit: 100 }, &quot;Rate limit approaching&quot;);</pre><p>Your log aggregator can then query userId:abc123 and surface every event for that user, in order, with full context.</p><h3>Testing Strategy</h3><h3>The Testing Pyramid</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_1v17RPCAhxbBy5sIeqww.png" /><figcaption>AI Generated Image</figcaption></figure><p>Heavily inverted pyramids, meaning too many E2E tests and too few unit tests, are slow, brittle, and expensive to maintain.</p><h3>Testing Server Actions</h3><pre>// actions/orders.test.ts<br>import { describe, it, expect, vi } from &quot;vitest&quot;;<br>import { createOrderAction } from &quot;./orders&quot;;<br><br>vi.mock(&quot;@/lib/db/queries/orders&quot;, () =&gt; ({<br>  createOrder: vi.fn().mockResolvedValue({ id: &quot;order_1&quot; }),<br>}));<br>vi.mock(&quot;@/lib/auth&quot;, () =&gt; ({<br>  requireAuth: vi.fn().mockResolvedValue({<br>    user: { id: &quot;user_1&quot;, email: &quot;test@test.com&quot; },<br>  }),<br>}));<br>vi.mock(&quot;next/cache&quot;, () =&gt; ({ revalidateTag: vi.fn() }));<br>vi.mock(&quot;next/navigation&quot;, () =&gt; ({ redirect: vi.fn() }));<br>describe(&quot;createOrderAction&quot;, () =&gt; {<br>  it(&quot;returns a validation error for invalid quantity&quot;, async () =&gt; {<br>    const formData = new FormData();<br>    formData.append(&quot;productId&quot;, &quot;123e4567-e89b-12d3-a456-426614174000&quot;);<br>    formData.append(&quot;quantity&quot;, &quot;0&quot;); // Below minimum of 1<br>    const result = await createOrderAction(formData);<br>    expect(result?.error).toBeDefined();<br>  });<br>  it(&quot;creates the order and revalidates the orders cache&quot;, async () =&gt; {<br>    const { createOrder } = await import(&quot;@/lib/db/queries/orders&quot;);<br>    const { revalidateTag } = await import(&quot;next/cache&quot;);<br>    const formData = new FormData();<br>    formData.append(&quot;productId&quot;, &quot;123e4567-e89b-12d3-a456-426614174000&quot;);<br>    formData.append(&quot;quantity&quot;, &quot;2&quot;);<br>    await createOrderAction(formData);<br>    expect(createOrder).toHaveBeenCalledWith({<br>      userId: &quot;user_1&quot;,<br>      productId: &quot;123e4567-e89b-12d3-a456-426614174000&quot;,<br>      quantity: 2,<br>    });<br>    expect(revalidateTag).toHaveBeenCalledWith(&quot;orders&quot;);<br>  });<br>});</pre><h3>Testing Commands (Domain Logic)</h3><p>Command functions are pure: no HTTP, no UI, just logic. They’re the most valuable tests to write because they cover the code most likely to break under changing requirements:</p><pre>// lib/commands/cancel-order.test.ts<br>import { describe, it, expect, vi } from &quot;vitest&quot;;<br>import { cancelOrder } from &quot;./cancel-order&quot;;<br>import { db } from &quot;@/lib/db&quot;;<br><br>vi.mock(&quot;@/lib/db&quot;);<br>vi.mock(&quot;@/lib/services/stripe&quot;);<br>vi.mock(&quot;@/lib/services/resend&quot;);<br>describe(&quot;cancelOrder&quot;, () =&gt; {<br>  it(&quot;throws if the order is already cancelled&quot;, async () =&gt; {<br>    vi.mocked(db.order.findFirstOrThrow).mockResolvedValue({<br>      status: &quot;cancelled&quot;,<br>    } as any);<br>    await expect(<br>      cancelOrder({ orderId: &quot;o1&quot;, userId: &quot;u1&quot;, reason: &quot;Changed mind&quot; })<br>    ).rejects.toThrow(&quot;Order is already cancelled&quot;);<br>  });<br>});</pre><h3>E2E Tests with Playwright</h3><p>E2E tests verify the full user journey. Keep them focused on critical paths:</p><pre>// e2e/checkout.spec.ts<br>import { test, expect } from &quot;@playwright/test&quot;;<br><br>test.describe(&quot;Checkout flow&quot;, () =&gt; {<br>  test.beforeEach(async ({ page }) =&gt; {<br>    await page.goto(&quot;/login&quot;);<br>    await page.fill(&#39;[name=&quot;email&quot;]&#39;, &quot;testuser@example.com&quot;);<br>    await page.fill(&#39;[name=&quot;password&quot;]&#39;, &quot;securepassword&quot;);<br>    await page.click(&#39;[type=&quot;submit&quot;]&#39;);<br>    await page.waitForURL(&quot;/dashboard&quot;);<br>  });<br>  test(&quot;user can add an item and complete checkout&quot;, async ({ page }) =&gt; {<br>    await page.goto(&quot;/products/sample-product&quot;);<br>    await page.click(&quot;text=Add to Cart&quot;);<br>    await expect(page.locator(&quot;[data-testid=cart-count]&quot;)).toHaveText(&quot;1&quot;);<br>    await page.goto(&quot;/checkout&quot;);<br>    await expect(page.locator(&quot;h1&quot;)).toContainText(&quot;Checkout&quot;);<br>    const stripeFrame = page.frameLocator(&quot;iframe[name*=stripe]&quot;);<br>    await stripeFrame.locator(&#39;[placeholder=&quot;Card number&quot;]&#39;).fill(&quot;4242424242424242&quot;);<br>    await stripeFrame.locator(&#39;[placeholder=&quot;MM / YY&quot;]&#39;).fill(&quot;12/29&quot;);<br>    await stripeFrame.locator(&#39;[placeholder=&quot;CVC&quot;]&#39;).fill(&quot;123&quot;);<br>    await page.click(&quot;text=Complete Purchase&quot;);<br>    await page.waitForURL(/\/orders\//);<br>    await expect(page.locator(&quot;h1&quot;)).toContainText(&quot;Order Confirmed&quot;);<br>  });<br>});</pre><p>Write E2E tests for checkout, login/signup, and any flow where a bug would have an immediate business impact. Edge cases belong in unit tests.</p><h3>CI/CD</h3><h3>GitHub Actions Pipeline</h3><pre># .github/workflows/ci.yml<br>name: CI<br><br>on:<br>  push:<br>    branches: [main]<br>  pull_request:<br>    branches: [main]<br>jobs:<br>  quality:<br>    name: Lint, Type-check &amp; Test<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: pnpm/action-setup@v3<br>        with:<br>          version: 9<br>      - uses: actions/setup-node@v4<br>        with:<br>          node-version: 20<br>          cache: pnpm<br>      - name: Install dependencies<br>        run: pnpm install --frozen-lockfile<br>      - name: Lint<br>        run: pnpm lint<br>      - name: Type-check<br>        run: pnpm type-check   # tsc --noEmit<br>      - name: Unit &amp; integration tests<br>        run: pnpm test --run<br>      - name: Build<br>        run: pnpm build<br>        env:<br>          DATABASE_URL: ${{ secrets.DATABASE_URL }}<br>          NEXTAUTH_SECRET: ${{ secrets.NEXTAUTH_SECRET }}<br>  e2e:<br>    name: E2E Tests<br>    needs: quality<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: pnpm/action-setup@v3<br>      - uses: actions/setup-node@v4<br>        with:<br>          node-version: 20<br>          cache: pnpm<br>      - run: pnpm install --frozen-lockfile<br>      - run: pnpm exec playwright install --with-deps chromium<br>      - name: Run E2E tests<br>        run: pnpm e2e<br>        env:<br>          BASE_URL: http://localhost:3000</pre><h3>Database Migration Safety</h3><p>Never run migrations automatically inside your build step. Migrations should be explicit, ordered, and rollback-aware:</p><pre>// package.json<br>{<br>  &quot;scripts&quot;: {<br>    &quot;db:migrate&quot;: &quot;prisma migrate deploy&quot;,<br>    &quot;db:generate&quot;: &quot;prisma generate&quot;,<br>    &quot;build&quot;: &quot;next build&quot;,<br>    &quot;type-check&quot;: &quot;tsc --noEmit&quot;<br>  }<br>}</pre><p>The correct deployment sequence is:</p><pre>1. db:migrate     Run pending migrations (fails fast if DB is unreachable)<br>2. build          Build the app (fails fast if type errors exist)<br>3. deploy         Swap traffic to new deployment</pre><p>If the migration fails, the build never runs. If the build fails, nothing is deployed. This sequencing prevents code that expects schema changes that haven’t landed yet from ever reaching production.</p><h3>Branch Protection Rules</h3><p>Enforce the pipeline before merging. In GitHub: require the quality and e2e jobs to pass, require at least one approval, and forbid force pushes to main. This makes the pipeline the actual gate rather than a recommendation.</p><h3>The Web Vitals Feedback Loop</h3><p>Set up <a href="https://vercel.com/analytics">Vercel Analytics</a> or the open-source web-vitals package to measure real-user performance:</p><pre>// app/layout.tsx<br>import { SpeedInsights } from &quot;@vercel/speed-insights/next&quot;;<br>import { Analytics } from &quot;@vercel/analytics/react&quot;;<br><br>export default function RootLayout({ children }: { children: React.ReactNode }) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        {children}<br>        &lt;Analytics /&gt;<br>        &lt;SpeedInsights /&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>Real User Monitoring shows you LCP, CLS, and INP scores for actual users on actual devices, not just a MacBook on a 1Gbps connection. The field data often tells a completely different story than your local Lighthouse score.</p><p>Check it weekly. The scores will drift as you add features. Catching a regression early means a five-minute fix rather than a two-day investigation.</p><h3>Closing Thoughts</h3><p>Across these three articles, the same underlying principle repeats: separating concerns by layer, being explicit about where data lives and how long it lives there, and making the failure modes loud and early rather than silent and late.</p><p>The individual patterns covered here are straightforward. What distinguishes production-grade codebases is applying them consistently, even when the shortcut is available. Next.js gives you the primitives. The discipline is what makes them scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cc69401fc4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Grade Next.js: Part 2, Design Patterns & Data]]></title>
            <link>https://medium.com/@kaveeshbc/building-production-grade-next-js-part-2-design-patterns-data-af76543beb4c?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/af76543beb4c</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 00:51:32 GMT</pubDate>
            <atom:updated>2026-06-16T23:32:53.157Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Repository pattern, Server Actions, caching, and error handling</h4><p><em>Part 2 of 3 — Design Patterns, File Structures &amp; Performance Engineering</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7CLyfoHMZsO7Jvaws1leA.png" /><figcaption>AI Generated Image</figcaption></figure><p><em>Missed </em><a href="https://medium.com/@kaveeshbc/building-production-grade-next-js-part-1-architecture-structure-c3b0e448d8f0"><em>Part 1</em></a><em>? Start there for the mental model, folder structure, and rendering strategies that underpin everything in this article.</em></p><p>Architecture is just intent. Patterns are how intent becomes code.</p><p>In <a href="https://medium.com/@kaveeshbc/building-production-grade-next-js-part-1-architecture-structure-c3b0e448d8f0">Part 1</a>, we covered the foundation: a layered mental model, a deliberate folder structure, and a framework for choosing the right rendering strategy. This article goes deeper into the application and domain layers where the real complexity lives. How do you talk to the database without coupling your UI to your ORM? How do you handle mutations, validation, and side effects without API routes cluttering your codebase? How do you cache without turning invalidation into a guessing game?</p><h3>The Repository Pattern for Data Access</h3><p>The most common coupling mistake in Next.js apps is importing Prisma (or Drizzle, or your DB client of choice) directly inside pages, layouts, and components. It works until you need to:</p><ul><li>Swap your ORM</li><li>Run the same query with a different filter from two places</li><li>Add caching or logging to data access</li><li>Write a unit test without a live database</li></ul><p>The Repository pattern fixes all of this by wrapping your database in a clean, typed API that the rest of your application consumes:</p><pre>// lib/db/queries/users.ts<br>import { db } from &quot;@/lib/db&quot;;<br>import type { User, CreateUserInput } from &quot;@/types/db&quot;;<br><br>export async function getUserById(id: string): Promise&lt;User | null&gt; {<br>  return db.user.findUnique({ where: { id } });<br>}<br>export async function getUserByEmail(email: string): Promise&lt;User | null&gt; {<br>  return db.user.findUnique({ where: { email } });<br>}<br>export async function createUser(input: CreateUserInput): Promise&lt;User&gt; {<br>  return db.user.create({ data: input });<br>}<br>export async function updateUser(<br>  id: string,<br>  data: Partial&lt;CreateUserInput&gt;<br>): Promise&lt;User&gt; {<br>  return db.user.update({ where: { id }, data });<br>}</pre><p>Server Components, Server Actions, and API routes should import from lib/db/queries/, never directly from db. When you need to add caching, you add it in one place, and every caller benefits automatically:</p><pre>// lib/db/queries/users.ts<br>import { cache } from &quot;react&quot;;<br>import { unstable_cache } from &quot;next/cache&quot;;<br>import { db } from &quot;@/lib/db&quot;;<br><br>// Request-level deduplication (same request, multiple callers get one DB hit)<br>export const getUserById = cache(async (id: string) =&gt; {<br>  return db.user.findUnique({ where: { id } });<br>});<br>// Cross-request caching (survives beyond the current request)<br>export const getCachedUserProfile = unstable_cache(<br>  async (id: string) =&gt; db.user.findUnique({<br>    where: { id },<br>    select: { id: true, name: true, avatarUrl: true, plan: true },<br>  }),<br>  [&quot;user-profile&quot;],<br>  { tags: [`user:${id}`], revalidate: 3600 }<br>);</pre><p>The caching layer is invisible to the rest of the application.</p><h3>The Database Singleton</h3><p>In development, hot-reloading creates new database connections on every module refresh. This exhausts connection pools quickly. Guard against it:</p><pre>// lib/db/index.ts<br>import { PrismaClient } from &quot;@prisma/client&quot;;<br><br>const globalForPrisma = globalThis as unknown as {<br>  prisma: PrismaClient | undefined;<br>};<br>export const db =<br>  globalForPrisma.prisma ??<br>  new PrismaClient({<br>    log: process.env.NODE_ENV === &quot;development&quot; ? [&quot;query&quot;, &quot;error&quot;] : [&quot;error&quot;],<br>  });<br>if (process.env.NODE_ENV !== &quot;production&quot;) {<br>  globalForPrisma.prisma = db;<br>}</pre><p>This gives you a single connection in development, clean pool management in production, and an identical import path everywhere.</p><h3>Server Actions as Your Application Layer</h3><p>Server Actions are the most underused primitive in the App Router. When used correctly, they eliminate the need for most API routes and give you a clean, type-safe application layer.</p><p>The ideal Server Action does exactly five things:</p><ol><li><strong>Authenticate:</strong> verify the caller is allowed</li><li><strong>Validate: </strong>parse and validate input with Zod</li><li><strong>Mutate: </strong>call the domain/repository layer</li><li><strong>Invalidate:</strong> bust affected cache entries</li><li><strong>Navigate: </strong>redirect or return a typed result</li></ol><pre>// actions/orders.ts<br>&quot;use server&quot;;<br><br>import { revalidateTag } from &quot;next/cache&quot;;<br>import { redirect } from &quot;next/navigation&quot;;<br>import { z } from &quot;zod&quot;;<br>import { requireAuth } from &quot;@/lib/auth&quot;;<br>import { createOrder } from &quot;@/lib/db/queries/orders&quot;;<br>import { sendOrderConfirmation } from &quot;@/lib/services/resend&quot;;<br>const CreateOrderSchema = z.object({<br>  productId: z.string().uuid(),<br>  quantity: z.number().int().min(1).max(100),<br>});<br>export async function createOrderAction(formData: FormData) {<br>  // 1. Auth<br>  const session = await requireAuth();<br>  // 2. Validate<br>  const parsed = CreateOrderSchema.safeParse({<br>    productId: formData.get(&quot;productId&quot;),<br>    quantity: Number(formData.get(&quot;quantity&quot;)),<br>  });<br>  if (!parsed.success) {<br>    return { error: parsed.error.flatten() };<br>  }<br>  // 3. Mutate<br>  const order = await createOrder({<br>    userId: session.user.id,<br>    ...parsed.data,<br>  });<br>  // Side effects (run after the primary mutation)<br>  await sendOrderConfirmation({ to: session.user.email, orderId: order.id });<br>  // 4. Invalidate<br>  revalidateTag(&quot;orders&quot;);<br>  // 5. Navigate<br>  redirect(`/orders/${order.id}`);<br>}</pre><p>No API route, no fetch, no manual JSON serialisation. The action is a direct, type-safe bridge between your UI and your domain layer.</p><h3>Using Server Actions in Forms</h3><pre>// components/forms/create-order-form.tsx<br>&quot;use client&quot;;<br>import { useFormState, useFormStatus } from &quot;react-dom&quot;;<br>import { createOrderAction } from &quot;@/actions/orders&quot;;<br><br>function SubmitButton() {<br>  const { pending } = useFormStatus();<br>  return (<br>    &lt;button type=&quot;submit&quot; disabled={pending}&gt;<br>      {pending ? &quot;Placing order...&quot; : &quot;Place order&quot;}<br>    &lt;/button&gt;<br>  );<br>}<br>export function CreateOrderForm({ productId }: { productId: string }) {<br>  const [state, action] = useFormState(createOrderAction, null);<br>  return (<br>    &lt;form action={action}&gt;<br>      &lt;input type=&quot;hidden&quot; name=&quot;productId&quot; value={productId} /&gt;<br>      &lt;input type=&quot;number&quot; name=&quot;quantity&quot; defaultValue={1} min={1} max={100} /&gt;<br>      {state?.error &amp;&amp; (<br>        &lt;p className=&quot;text-red-500&quot;&gt;Something went wrong. Please try again.&lt;/p&gt;<br>      )}<br>      &lt;SubmitButton /&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>Progressive enhancement comes for free: the form works without JavaScript. The pending state comes from useFormStatus without custom state management. Validation errors from the action surface directly.</p><h3>Type-Safe Environment Variables</h3><p>The most common source of mysterious production bugs is misconfigured environment variables discovered at runtime rather than at startup. Validate them the moment the process boots:</p><pre>// config/env.ts<br>import { z } from &quot;zod&quot;;<br><br>const envSchema = z.object({<br>  DATABASE_URL: z.string().url(),<br>  NEXTAUTH_SECRET: z.string().min(32),<br>  NEXTAUTH_URL: z.string().url(),<br>  STRIPE_SECRET_KEY: z.string().startsWith(&quot;sk_&quot;),<br>  STRIPE_WEBHOOK_SECRET: z.string().startsWith(&quot;whsec_&quot;),<br>  RESEND_API_KEY: z.string(),<br>  REVALIDATE_SECRET: z.string().min(20),<br>  NODE_ENV: z.enum([&quot;development&quot;, &quot;test&quot;, &quot;production&quot;]),<br>});<br>const parsed = envSchema.safeParse(process.env);<br>if (!parsed.success) {<br>  console.error(<br>    &quot;❌ Invalid environment variables:&quot;,<br>    JSON.stringify(parsed.error.format(), null, 2)<br>  );<br>  process.exit(1);<br>}<br>export const env = parsed.data;</pre><p>Import env from @/config/env everywhere, never process.env directly. You get full autocomplete, type safety, and a crash at startup with a clear error message rather than a silent failure discovered by an end user.</p><h3>The Command Pattern for Complex Mutations</h3><p>When a business operation grows beyond validation and a single DB call, pull it into a dedicated command function. This is where your domain logic lives: pure, testable, and with no knowledge of HTTP or the UI.</p><pre>// lib/commands/cancel-order.ts<br>import { db } from &quot;@/lib/db&quot;;<br>import { refundPayment } from &quot;@/lib/services/stripe&quot;;<br>import { sendCancellationEmail } from &quot;@/lib/services/resend&quot;;<br>import { revalidateTag } from &quot;next/cache&quot;;<br><br>interface CancelOrderInput {<br>  orderId: string;<br>  userId: string;<br>  reason: string;<br>}<br>export async function cancelOrder({<br>  orderId,<br>  userId,<br>  reason,<br>}: CancelOrderInput) {<br>  const order = await db.order.findFirstOrThrow({<br>    where: { id: orderId, userId },<br>  });<br>  if (order.status === &quot;cancelled&quot;) {<br>    throw new Error(&quot;Order is already cancelled&quot;);<br>  }<br>  // Atomic DB mutation<br>  await db.$transaction(async (tx) =&gt; {<br>    await tx.order.update({<br>      where: { id: orderId },<br>      data: { status: &quot;cancelled&quot;, cancelReason: reason },<br>    });<br>    await tx.orderEvent.create({<br>      data: { orderId, type: &quot;CANCELLED&quot;, metadata: { reason } },<br>    });<br>  });<br>  // Side effects run outside the transaction, so they can retry independently<br>  await refundPayment(order.paymentIntentId);<br>  await sendCancellationEmail(order.userEmail);<br>  revalidateTag(`order:${orderId}`);<br>  revalidateTag(&quot;orders&quot;);<br>}</pre><p>The Server Action becomes a thin orchestration layer that validates, authorises, and calls the command:</p><pre>// actions/orders.ts<br>&quot;use server&quot;;<br><br>export async function cancelOrderAction(orderId: string, reason: string) {<br>  const session = await requireAuth();<br>  await cancelOrder({ orderId, userId: session.user.id, reason });<br>  redirect(&quot;/orders&quot;);<br>}</pre><p>This separation makes domain logic independently testable. No mocking of request objects, no HTTP concerns, just a pure function with observable output.</p><h3>A Caching Strategy That Holds Up</h3><h3>The Three Layers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTkIIPPcHrI-wvlGvmTQ_Q.png" /><figcaption>AI Generated Image</figcaption></figure><p>Understanding which layer holds your data determines how you invalidate it. A revalidateTag call clears the Data Cache. Navigating in the browser can draw from the Router Cache. A new deployment busts the Full Route Cache for statically generated pages.</p><h3>Centralising Cache Keys</h3><p>Typos in cache tag strings cause silent bugs that are nearly impossible to debug. Centralise every key in a registry:</p><pre>// lib/cache/keys.ts<br>export const CacheKeys = {<br>  user: (id: string) =&gt; `user:${id}`,<br>  userOrders: (userId: string) =&gt; `user:${userId}:orders`,<br>  product: (id: string) =&gt; `product:${id}`,<br>  products: &quot;products&quot;,<br>  orders: &quot;orders&quot;,<br>} as const;</pre><p>Then expose typed invalidation helpers:</p><pre>// lib/cache/revalidate.ts<br>import { revalidateTag } from &quot;next/cache&quot;;<br>import { CacheKeys } from &quot;./keys&quot;;<br><br>export function invalidateUser(userId: string) {<br>  revalidateTag(CacheKeys.user(userId));<br>  revalidateTag(CacheKeys.userOrders(userId));<br>}<br>export function invalidateProducts() {<br>  revalidateTag(CacheKeys.products);<br>}</pre><p>Server Actions call invalidateUser(userId) rather than string literals. Refactoring a cache key is a one-line change in keys.ts.</p><h3>unstable_cache for Database Queries</h3><p>fetch() participates in the Data Cache automatically. Prisma and Drizzle queries do not, so they need unstable_cache:</p><pre>// lib/db/queries/products.ts<br>import { unstable_cache } from &quot;next/cache&quot;;<br>import { CacheKeys } from &quot;@/lib/cache/keys&quot;;<br>import { db } from &quot;@/lib/db&quot;;<br><br>export const getCachedProducts = unstable_cache(<br>  async () =&gt;<br>    db.product.findMany({<br>      where: { active: true },<br>      orderBy: { createdAt: &quot;desc&quot; },<br>    }),<br>  [&quot;products-list&quot;],<br>  {<br>    tags: [CacheKeys.products],<br>    revalidate: 300, // 5-minute fallback<br>  }<br>);</pre><p>Knowing when to use react cache() vs unstable_cache matters:</p><p>react cache() unstable_cache Scope Single request Across requests Storage In-memory (request lifecycle) Persistent (Data Cache) Invalidation Automatic when request ends revalidateTag Use case Deduplication within a render, Cross-request caching</p><p>Use react cache() to prevent duplicate DB calls within a single render tree. Use unstable_cache to cache results across multiple requests.</p><h3>Error Handling: Type-Safe Results from Server Actions</h3><p>Rather than letting errors propagate as unhandled exceptions, use a discriminated union result type. It makes error states explicit, typed, and composable:</p><pre>// types/api.ts<br>export type ActionResult&lt;T&gt; =<br>  | { success: true; data: T }<br>  | { success: false; error: string; fieldErrors?: Record&lt;string, string[]&gt; };<br><br>// actions/users.ts<br>export async function updateProfileAction(<br>  formData: FormData<br>): Promise&lt;ActionResult&lt;User&gt;&gt; {<br>  try {<br>    const session = await requireAuth();<br>    const parsed = UpdateProfileSchema.safeParse(<br>      Object.fromEntries(formData)<br>    );<br>    if (!parsed.success) {<br>      return {<br>        success: false,<br>        error: &quot;Validation failed&quot;,<br>        fieldErrors: parsed.error.flatten().fieldErrors,<br>      };<br>    }<br>    const user = await updateUser(session.user.id, parsed.data);<br>    revalidateTag(CacheKeys.user(session.user.id));<br>    return { success: true, data: user };<br>  } catch (err) {<br>    // Log to your error tracking service here<br>    return { success: false, error: &quot;Failed to update profile&quot; };<br>  }<br>}</pre><p>The client component handles both outcomes explicitly:</p><pre>&quot;use client&quot;;<br>import { updateProfileAction } from &quot;@/actions/users&quot;;<br><br>export function ProfileForm({ user }: { user: User }) {<br>  async function handleSubmit(formData: FormData) {<br>    const result = await updateProfileAction(formData);<br>    if (!result.success) {<br>      // Show field errors or generic error<br>      return;<br>    }<br>    // result.data is typed as User here, no casting needed<br>    toast.success(`Profile updated for ${result.data.name}`);<br>  }<br>  return &lt;form action={handleSubmit}&gt;{/* fields */}&lt;/form&gt;;<br>}</pre><p>TypeScript knows the shape of result in each branch. No try/catch in the component, no runtime guessing.</p><p><a href="https://medium.com/@kaveeshbc/building-production-grade-next-js-part-3-performance-security-shipping-6cc69401fc4c">Part 3</a> covers the final layer: image, font, and bundle optimisation, edge middleware for authentication, observability with OpenTelemetry and structured logging, a practical testing strategy, and the CI/CD pipeline that keeps everything green on every push.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af76543beb4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Grade Next.js: Part 1, Architecture & Structure]]></title>
            <link>https://medium.com/@kaveeshbc/building-production-grade-next-js-part-1-architecture-structure-c3b0e448d8f0?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3b0e448d8f0</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 22:25:57 GMT</pubDate>
            <atom:updated>2026-06-16T23:36:09.770Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to think about your app before writing a single line of code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8be-26xzFNA5Z-c1CHhDEQ.png" /><figcaption>AI Generated Image</figcaption></figure><p><em>Part 1 of 3 — Design Patterns, File Structures &amp; Performance Engineering. A field guide for engineers who build things that actually have to survive contact with real users.</em></p><p>There’s a meaningful gap between a Next.js app that works and one that scales. The difference isn’t magic. It’s the accumulation of hundreds of intentional decisions: how you structure your files, which data-fetching strategy you pick, where you draw boundaries between server and client code, and whether your architecture can absorb new features without turning into a house of cards.</p><p>This three-part series covers all of it, moving from first principles to concrete implementation across design patterns, folder structure, rendering strategies, caching, observability, and CI/CD.</p><ul><li><strong>Part 1 (this article):</strong> The mental model, file structure, and rendering strategies</li><li><a href="https://medium.com/@kaveeshbc/building-production-grade-next-js-part-2-design-patterns-data-af76543beb4c"><strong>Part 2:</strong> Design patterns and data: Repository pattern, Server Actions, caching</a></li><li><a href="https://medium.com/@kaveeshbc/building-production-grade-next-js-part-3-performance-security-shipping-6cc69401fc4c"><strong>Part 3:</strong> Performance, security, testing, and shipping to production</a></li></ul><h3>The Mental Model: Think in Layers</h3><p>Before touching a single file, internalize the layered architecture that underpins every scalable Next.js application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDWDVnM3D9EV0T6u_isftg.png" /><figcaption>AI Generated Image</figcaption></figure><p>Each layer communicates <strong>only with the layer directly below it</strong>. Presentation never touches infrastructure. This single rule prevents the spaghetti that kills most growing codebases. When a junior engineer asks <em>“where does this belong?”</em>, the answer should be obvious from which layer the code operates in, not a matter of team debate.</p><p>Hold this model in your head as you read the rest of this series. Every pattern covered is an expression of it.</p><h3>File &amp; Folder Structure</h3><p>Good structure doesn’t just organise code. It communicates intent and enforces the layered architecture automatically.</p><h3>The Canonical Structure</h3><pre>my-app/<br>├── app/                        # Next.js App Router root<br>│   ├── (marketing)/            # Route group (no URL segment)<br>│   │   ├── page.tsx<br>│   │   └── layout.tsx<br>│   ├── (dashboard)/<br>│   │   ├── layout.tsx<br>│   │   ├── analytics/<br>│   │   │   └── page.tsx<br>│   │   └── settings/<br>│   │       └── page.tsx<br>│   ├── api/<br>│   │   └── webhooks/<br>│   │       └── stripe/<br>│   │           └── route.ts<br>│   ├── layout.tsx              # Root layout<br>│   ├── globals.css<br>│   └── not-found.tsx<br>│<br>├── components/<br>│   ├── ui/                     # Primitive, reusable UI atoms<br>│   │   ├── button.tsx<br>│   │   ├── card.tsx<br>│   │   └── dialog.tsx<br>│   ├── forms/                  # Composed form components<br>│   │   ├── login-form.tsx<br>│   │   └── checkout-form.tsx<br>│   └── layouts/                # Structural layout components<br>│       ├── header.tsx<br>│       └── sidebar.tsx<br>│<br>├── lib/                        # Domain + infrastructure<br>│   ├── db/<br>│   │   ├── index.ts            # Singleton DB client (Prisma / Drizzle)<br>│   │   └── queries/<br>│   │       ├── users.ts<br>│   │       └── orders.ts<br>│   ├── cache/<br>│   │   ├── keys.ts             # Centralised cache key registry<br>│   │   └── revalidate.ts<br>│   ├── services/               # Third-party integrations<br>│   │   ├── stripe.ts<br>│   │   ├── resend.ts<br>│   │   └── s3.ts<br>│   └── utils/<br>│       ├── cn.ts               # className merging utility<br>│       ├── format.ts<br>│       └── validation.ts<br>│<br>├── hooks/                      # Custom React hooks (client-side)<br>│   ├── use-debounce.ts<br>│   └── use-media-query.ts<br>│<br>├── actions/                    # Server Actions<br>│   ├── auth.ts<br>│   ├── orders.ts<br>│   └── users.ts<br>│<br>├── types/                      # Shared TypeScript types<br>│   ├── api.ts<br>│   ├── db.ts<br>│   └── globals.d.ts<br>│<br>├── config/                     # Static configuration<br>│   ├── site.ts                 # Site metadata, nav links<br>│   └── env.ts                  # Type-safe env validation<br>│<br>├── middleware.ts               # Auth guards, redirects, A/B flags<br>├── next.config.ts<br>├── tailwind.config.ts<br>└── tsconfig.json</pre><p>Every directory has a single, clear responsibility. If a file doesn’t have an obvious home, that’s a signal: either the abstraction is missing, or the file is doing too much.</p><h3>Why Route Groups Matter</h3><p>Route groups ((marketing), (dashboard)) let you share layouts without leaking them across the whole app. Marketing pages get a minimal layout; the dashboard gets a sidebar and topbar layout, with no duplication required.</p><pre>// app/(dashboard)/layout.tsx<br>import { Sidebar } from &quot;@/components/layouts/sidebar&quot;;<br>import { Topbar } from &quot;@/components/layouts/topbar&quot;;<br>import { requireAuth } from &quot;@/lib/auth&quot;;<br><br>export default async function DashboardLayout({<br>  children,<br>}: {<br>  children: React.ReactNode;<br>}) {<br>  await requireAuth(); // Throws, caught by error boundary or middleware redirect<br>  return (<br>    &lt;div className=&quot;flex h-screen&quot;&gt;<br>      &lt;Sidebar /&gt;<br>      &lt;main className=&quot;flex-1 overflow-y-auto&quot;&gt;<br>        &lt;Topbar /&gt;<br>        {children}<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The layout enforces authentication for every route inside (dashboard) without repeating the check on individual pages. Change the auth logic once, and it applies everywhere inside the group.</p><h3>Feature-Based Colocation for Larger Teams</h3><p>For teams of five or more engineers, co-locating by feature scales better than co-locating by type:</p><pre>features/<br>├── auth/<br>│   ├── components/<br>│   ├── hooks/<br>│   ├── actions.ts<br>│   └── schemas.ts<br>├── billing/<br>│   ├── components/<br>│   ├── hooks/<br>│   ├── actions.ts<br>│   └── schemas.ts</pre><p>Feature ownership becomes explicit. An engineer working on billing doesn’t need to navigate across components/, hooks/, actions/, and lib/ to understand a single flow. Everything lives together.</p><p>The tradeoff: truly shared, primitive UI components (Button, Dialog, Input) still belong in a global components/ui/ directory. Feature folders are for feature-specific composition, not design system atoms.</p><h3>Rendering Strategies: Choosing Deliberately</h3><p>Next.js gives you four rendering strategies. Choosing the wrong one is the most common cause of unnecessary server load and poor UX.</p><h3>The Decision Matrix</h3><p>Strategy When to use Data freshness <strong>Static (SSG)</strong> Marketing pages, docs, blogs Build time <strong>ISR</strong> Content that changes occasionally Configurable interval <strong>SSR (Dynamic)</strong> Personalised, real-time, auth-gated Per request <strong>Client-Side</strong> Highly interactive, user-specific post-hydration On demand</p><p>The default instinct for many developers is to reach for SSR because it feels safe. But serving a fully dynamic response for a page that changes twice a week is wasteful. Static and ISR pages are faster, cheaper to serve, and more resilient because they survive origin downtime behind a CDN.</p><h3>Static Generation with generateStaticParams</h3><pre>// app/blog/[slug]/page.tsx<br>import { getAllSlugs, getPost } from &quot;@/lib/db/queries/posts&quot;;<br><br>export async function generateStaticParams() {<br>  const slugs = await getAllSlugs();<br>  return slugs.map((slug) =&gt; ({ slug }));<br>}<br>export default async function BlogPost({<br>  params,<br>}: {<br>  params: { slug: string };<br>}) {<br>  const post = await getPost(params.slug);<br>  return &lt;article&gt;{/* render post */}&lt;/article&gt;;<br>}</pre><p>All slugs are pre-rendered at build time. The CDN serves them. Your database gets zero traffic from blog page views.</p><h3>ISR for Dynamic Content</h3><p>Incremental Static Regeneration gives you static performance with eventual freshness:</p><pre>// Revalidate the entire route every 60 seconds<br>export const revalidate = 60;<br><br>// Or at the individual fetch level:<br>const data = await fetch(&quot;https://api.example.com/products&quot;, {<br>  next: { revalidate: 300 }, // 5 minutes per request<br>});</pre><p>The background regeneration model means users always get a cached response rather than a loading spinner from a cold server, while the data stays reasonably fresh.</p><h3>On-Demand Revalidation</h3><p>ISR with a fixed timer is reactive, not intelligent. Content updates at an arbitrary interval regardless of whether anything has changed. On-demand revalidation solves this: your CMS fires a webhook the moment a post is published, and you bust only the affected cache entries.</p><pre>// app/api/revalidate/route.ts<br>import { revalidatePath, revalidateTag } from &quot;next/cache&quot;;<br>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br><br>export async function POST(req: NextRequest) {<br>  const secret = req.headers.get(&quot;x-revalidate-secret&quot;);<br>  if (secret !== process.env.REVALIDATE_SECRET) {<br>    return NextResponse.json({ error: &quot;Unauthorized&quot; }, { status: 401 });<br>  }<br>  const { path, tag } = await req.json();<br>  if (tag) revalidateTag(tag);<br>  if (path) revalidatePath(path);<br>  return NextResponse.json({ revalidated: true });<br>}</pre><p>Tag your fetches at the data-access layer:</p><pre>const products = await fetch(&quot;/api/products&quot;, {<br>  next: { tags: [&quot;products&quot;] },<br>});</pre><p>When a product is updated, the webhook calls /api/revalidate with { tag: &quot;products&quot; }. Only those cached responses are purged.</p><h3>Server Components vs Client Components</h3><p>This is where most teams leave significant performance on the table.</p><p><strong>Everything is a Server Component by default.</strong> Only add &quot;use client&quot; when you need:</p><ul><li>useState / useReducer</li><li>useEffect</li><li>Browser APIs (window, document, navigator)</li><li>Event listeners</li></ul><p>Server Components never ship to the client bundle. They execute on the server, produce HTML or an RSC payload, and are done. A Server Component that imports a 200KB charting library adds zero kilobytes to the user’s download.</p><h3>Keep the Boundary Low</h3><p>Keep the &quot;use client&quot; boundary as low in the tree as possible:</p><pre>// ✅ GOOD — Server Component fetches data, passes minimal props to client<br>// app/dashboard/page.tsx<br>import { getUser } from &quot;@/lib/db/queries/users&quot;;<br>import { LikeButton } from &quot;./like-button&quot;; // Client Component<br><br>export default async function Dashboard() {<br>  const user = await getUser();<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Hello, {user.name}&lt;/h1&gt;<br>      {/* Only this leaf becomes a Client Component */}<br>      &lt;LikeButton initialCount={user.likedPosts} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// ❌ BAD — Making the entire page a Client Component for one interactive element<br>&quot;use client&quot;;<br>import { useState, useEffect } from &quot;react&quot;;<br><br>export default function Dashboard() {<br>  const [user, setUser] = useState(null);<br>  useEffect(() =&gt; {<br>    fetch(&quot;/api/user&quot;).then(r =&gt; r.json()).then(setUser);<br>  }, []);<br>  // No SSR, no caching, worse performance - just to render a like button<br>}</pre><p>The bad pattern kills SSR, loses caching, flashes a loading state, and ships everything to the client, all to handle a single interactive element.</p><h3>Passing Server Components as Children to Client Components</h3><p>A pattern many developers miss: you can pass Server Components <em>through</em> Client Components using the children prop. This lets a Client Component wrapper manage UI state while its contents remain server-rendered.</p><pre>// components/collapsible-section.tsx<br>&quot;use client&quot;;<br>import { useState } from &quot;react&quot;;<br><br>export function CollapsibleSection({<br>  title,<br>  children,<br>}: {<br>  title: string;<br>  children: React.ReactNode;<br>}) {<br>  const [open, setOpen] = useState(true);<br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setOpen(!open)}&gt;{title}&lt;/button&gt;<br>      {open &amp;&amp; children}<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// app/dashboard/page.tsx (Server Component)<br>import { CollapsibleSection } from &quot;@/components/collapsible-section&quot;;<br>import { OrderHistory } from &quot;./order-history&quot;; // Server Component, heavy DB query<br><br>export default function DashboardPage() {<br>  return (<br>    &lt;CollapsibleSection title=&quot;Recent Orders&quot;&gt;<br>      &lt;OrderHistory /&gt; {/* Still a Server Component - runs on the server */}<br>    &lt;/CollapsibleSection&gt;<br>  );<br>}</pre><p>OrderHistory runs on the server and streams in. It never touches the client bundle. The CollapsibleSection manages toggle state on the client. Both coexist without any workarounds.</p><p>Part 2 goes deeper into the application and domain layers: the Repository pattern for data access, Server Actions as your application layer, type-safe environment validation, the command pattern for complex business logic, and a caching strategy that holds up under real production traffic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3b0e448d8f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Cost-Effective Serverless Architecture on AWS That Scales to 1,000+ Users]]></title>
            <link>https://aws.plainenglish.io/building-a-cost-effective-serverless-architecture-on-aws-that-scales-to-1-000-users-fb3449f80758?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb3449f80758</guid>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-cost-optimization]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 23:17:40 GMT</pubDate>
            <atom:updated>2026-06-16T23:36:49.106Z</atom:updated>
            <content:encoded><![CDATA[<p>How to go from zero to production without managing a single server and without breaking the bank</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BjOC4hMlczhkkG-LdqVfPg.png" /><figcaption>AI Generated Image</figcaption></figure><p>When most developers hear “scalable architecture,” they picture Kubernetes clusters, load balancers, and DevOps engineers. But with AWS’s serverless ecosystem, you can build something that scales to thousands of users, costs next to nothing at low traffic, and requires zero server management, all in an afternoon.</p><p>This guide walks through designing and deploying a simple, cost-effective serverless architecture on AWS, complete with setup commands and configuration code you can follow step by step.</p><h3>The Architecture at a Glance</h3><p>Before diving into setup, here’s the stack we’ll be building:</p><pre>Client (Browser / Mobile App)<br>        │<br>        ▼<br>   CloudFront (CDN)<br>        │<br>        ├──► S3 (Static Frontend Assets)<br>        │<br>        └──► API Gateway (REST or HTTP API)<br>                  │<br>                  ▼<br>            Lambda Functions<br>                  │<br>        ┌─────────┴──────────┐<br>        ▼                    ▼<br>   DynamoDB             S3 (File Storage)<br>        │<br>        ▼<br>   SES / SNS (Notifications)</pre><p>Every component here is fully managed, auto-scaling, and billed only on actual usage. At 1,000 users, your monthly AWS bill will likely sit between <strong>$5 and $20 USD,</strong> depending on traffic patterns.</p><h3>Why Serverless?</h3><p>Before the setup guide, here’s why this approach wins for early-to-mid stage products:</p><p><strong>Cost at low scale:</strong> With AWS Lambda’s free tier giving you 1 million requests per month and DynamoDB’s free tier covering 25 GB of storage, you can run a real product at essentially zero cost until you hit meaningful traffic.</p><p><strong>Auto-scaling built in:</strong> Lambda scales from 1 request to 10,000+ concurrent requests automatically, with no configuration. DynamoDB on-demand mode scales with your traffic instantly.</p><p><strong>No ops overhead:</strong> No patching servers, no capacity planning, no SSH-ing into machines at 2 AM. AWS manages the infrastructure entirely.</p><p><strong>Pay-per-use pricing:</strong> You’re billed only when your functions execute. Idle time costs nothing.</p><h3>Prerequisites</h3><p>Make sure you have the following before starting:</p><ul><li>An AWS account (free tier is fine to start)</li><li>AWS CLI installed and configured (aws configure)</li><li>Node.js 18+ installed</li><li>Basic familiarity with terminal/command line</li></ul><p>Install the AWS CLI if you haven’t:</p><pre># macOS<br>brew install awscli<br><br># Linux<br>curl &quot;https://awsdocs.s3.amazonaws.com/cli/latest/awscli-exe-linux-x86_64.zip&quot; -o &quot;awscliv2.zip&quot;<br>unzip awscliv2.zip &amp;&amp; sudo ./aws/install<br><br># Configure with your credentials<br>aws configure<br># Enter: AWS Access Key ID, Secret Access Key, Region (e.g. us-east-1), Output format (json)</pre><h3>Step 1: Set Up DynamoDB</h3><p>DynamoDB is our database. We’ll create a single table using on-demand billing, which means you pay per read/write, not for provisioned capacity.</p><pre>aws dynamodb create-table \<br>  --table-name AppUsers \<br>  --attribute-definitions \<br>    AttributeName=userId,AttributeType=S \<br>    AttributeName=createdAt,AttributeType=S \<br>  --key-schema \<br>    AttributeName=userId,KeyType=HASH \<br>    AttributeName=createdAt,KeyType=RANGE \<br>  --billing-mode PAY_PER_REQUEST \<br>  --region us-east-1</pre><p><strong>Why on-demand mode?</strong> With provisioned capacity, you pay for the throughput you reserve, whether or not you use it. On-demand scales automatically and is perfect until you’re consistently running millions of requests per day.</p><p>Verify the table was created:</p><pre>aws dynamodb describe-table --table-name AppUsers --query &#39;Table.TableStatus&#39;</pre><h3>Step 2: Set Up S3 Buckets</h3><p>We need two S3 buckets, one for the static frontend, one for user uploads.</p><pre># Frontend assets bucket<br>aws s3 mb s3://your-app-frontend-assets --region us-east-1<br><br># Configure it for static website hosting<br>aws s3 website s3://your-app-frontend-assets \<br>  --index-document index.html \<br>  --error-document index.html<br><br># User uploads bucket (private)<br>aws s3 mb s3://your-app-user-uploads --region us-east-1</pre><p>Set a bucket policy for the frontend so CloudFront can access it (we’ll tie this to CloudFront in a later step):</p><pre>cat &gt; bucket-policy.json &lt;&lt; &#39;EOF&#39;<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: &quot;*&quot;,<br>      &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::your-app-frontend-assets/*&quot;<br>    }<br>  ]<br>}<br>EOF<br><br>aws s3api put-bucket-policy \<br>  --bucket your-app-frontend-assets \<br>  --policy file://bucket-policy.json</pre><h3>Step 3: Create Lambda Functions</h3><p>Lambda is the compute layer where every API endpoint becomes a Lambda function. Here’s how to set up a simple user creation endpoint.</p><h3>Create an IAM Role for Lambda</h3><p>Lambda functions need permissions to access DynamoDB and other AWS services:</p><pre># Create the trust policy<br>cat &gt; lambda-trust-policy.json &lt;&lt; &#39;EOF&#39;<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: { &quot;Service&quot;: &quot;lambda.amazonaws.com&quot; },<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>    }<br>  ]<br>}<br>EOF<br><br># Create the role<br>aws iam create-role \<br>  --role-name lambda-serverless-role \<br>  --assume-role-policy-document file://lambda-trust-policy.json<br># Attach basic execution policy (CloudWatch logs)<br>aws iam attach-role-policy \<br>  --role-name lambda-serverless-role \<br>  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole<br># Attach DynamoDB full access (scope this down in production)<br>aws iam attach-role-policy \<br>  --role-name lambda-serverless-role \<br>  --policy-arn arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess</pre><h3>Write Your First Lambda Function</h3><p>Create a file called createUser.js:</p><pre>const { DynamoDBClient } = require(&quot;@aws-sdk/client-dynamodb&quot;);<br>const { DynamoDBDocumentClient, PutCommand } = require(&quot;@aws-sdk/lib-dynamodb&quot;);<br>const { randomUUID } = require(&quot;crypto&quot;);<br><br>const client = new DynamoDBClient({ region: &quot;us-east-1&quot; });<br>const docClient = DynamoDBDocumentClient.from(client);<br>exports.handler = async (event) =&gt; {<br>  const headers = {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;,<br>  };<br>  try {<br>    const body = JSON.parse(event.body || &quot;{}&quot;);<br>    const { name, email } = body;<br>    if (!name || !email) {<br>      return {<br>        statusCode: 400,<br>        headers,<br>        body: JSON.stringify({ error: &quot;name and email are required&quot; }),<br>      };<br>    }<br>    const userId = randomUUID();<br>    const createdAt = new Date().toISOString();<br>    await docClient.send(<br>      new PutCommand({<br>        TableName: &quot;AppUsers&quot;,<br>        Item: { userId, createdAt, name, email },<br>        ConditionExpression: &quot;attribute_not_exists(userId)&quot;,<br>      })<br>    );<br>    return {<br>      statusCode: 201,<br>      headers,<br>      body: JSON.stringify({ userId, name, email, createdAt }),<br>    };<br>  } catch (error) {<br>    console.error(&quot;Error:&quot;, error);<br>    return {<br>      statusCode: 500,<br>      headers,<br>      body: JSON.stringify({ error: &quot;Internal server error&quot; }),<br>    };<br>  }<br>};</pre><h3>Deploy the Lambda Function</h3><pre># Install AWS SDK v3 (if needed)<br>npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb<br><br># Zip the function<br>zip -r createUser.zip createUser.js node_modules/<br><br># Get your account ID<br>ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)<br><br># Deploy<br>aws lambda create-function \<br>  --function-name createUser \<br>  --runtime nodejs18.x \<br>  --role arn:aws:iam::${ACCOUNT_ID}:role/lambda-serverless-role \<br>  --handler createUser.handler \<br>  --zip-file fileb://createUser.zip \<br>  --timeout 10 \<br>  --memory-size 256 \<br>  --region us-east-1</pre><p><strong>Memory and timeout tuning:</strong> 256 MB is a good starting point. Lambda pricing is based on memory × duration, so don’t over-allocate. You can always increase it if needed.</p><h3>Step 4: Set Up API Gateway</h3><p>API Gateway sits in front of Lambda and routes HTTP requests to the right function. We’ll use the HTTP API (not REST API), it’s faster and cheaper.</p><pre># Create the HTTP API<br>API_ID=$(aws apigatewayv2 create-api \<br>  --name &quot;ServerlessApp&quot; \<br>  --protocol-type HTTP \<br>  --cors-configuration \<br>    AllowOrigins=&quot;*&quot;,AllowMethods=&quot;GET,POST,PUT,DELETE,OPTIONS&quot;,AllowHeaders=&quot;Content-Type,Authorization&quot; \<br>  --query &#39;ApiId&#39; \<br>  --output text)<br><br>echo &quot;API ID: $API_ID&quot;<br># Create a Lambda integration<br>ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)<br>INTEGRATION_ID=$(aws apigatewayv2 create-integration \<br>  --api-id $API_ID \<br>  --integration-type AWS_PROXY \<br>  --integration-uri arn:aws:lambda:us-east-1:${ACCOUNT_ID}:function:createUser \<br>  --payload-format-version 2.0 \<br>  --query &#39;IntegrationId&#39; \<br>  --output text)<br># Create a route<br>aws apigatewayv2 create-route \<br>  --api-id $API_ID \<br>  --route-key &quot;POST /users&quot; \<br>  --target integrations/$INTEGRATION_ID<br># Deploy the API<br>aws apigatewayv2 create-stage \<br>  --api-id $API_ID \<br>  --stage-name prod \<br>  --auto-deploy<br># Give API Gateway permission to invoke Lambda<br>aws lambda add-permission \<br>  --function-name createUser \<br>  --statement-id apigateway-invoke \<br>  --action lambda:InvokeFunction \<br>  --principal apigateway.amazonaws.com \<br>  --source-arn &quot;arn:aws:execute-api:us-east-1:${ACCOUNT_ID}:${API_ID}/*/*/users&quot;</pre><p>Retrieve your API endpoint:</p><pre>aws apigatewayv2 get-api \<br>  --api-id $API_ID \<br>  --query &#39;ApiEndpoint&#39; \<br>  --output text</pre><p>You’ll get a URL like https://abc123xyz.execute-api.us-east-1.amazonaws.com. Your endpoint is POST /prod/users.</p><p>Test it:</p><pre>curl -X POST https://abc123xyz.execute-api.us-east-1.amazonaws.com/prod/users \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;name&quot;: &quot;Alice&quot;, &quot;email&quot;: &quot;alice@example.com&quot;}&#39;</pre><h3>Step 5: Deploy the Frontend with CloudFront</h3><p>CloudFront is AWS’s CDN. It caches your frontend assets at edge locations worldwide, meaning fast load times for users regardless of geography.</p><pre># Create a CloudFront distribution pointing to the S3 bucket<br>aws cloudfront create-distribution \<br>  --distribution-config &#39;{<br>    &quot;CallerReference&quot;: &quot;my-app-dist-1&quot;,<br>    &quot;Origins&quot;: {<br>      &quot;Quantity&quot;: 1,<br>      &quot;Items&quot;: [{<br>        &quot;Id&quot;: &quot;S3-frontend&quot;,<br>        &quot;DomainName&quot;: &quot;your-app-frontend-assets.s3.amazonaws.com&quot;,<br>        &quot;S3OriginConfig&quot;: { &quot;OriginAccessIdentity&quot;: &quot;&quot; }<br>      }]<br>    },<br>    &quot;DefaultCacheBehavior&quot;: {<br>      &quot;TargetOriginId&quot;: &quot;S3-frontend&quot;,<br>      &quot;ViewerProtocolPolicy&quot;: &quot;redirect-to-https&quot;,<br>      &quot;CachePolicyId&quot;: &quot;658327ea-f89d-4fab-a63d-7e88639e58f6&quot;,<br>      &quot;AllowedMethods&quot;: {<br>        &quot;Quantity&quot;: 2,<br>        &quot;Items&quot;: [&quot;HEAD&quot;, &quot;GET&quot;],<br>        &quot;CachedMethods&quot;: { &quot;Quantity&quot;: 2, &quot;Items&quot;: [&quot;HEAD&quot;, &quot;GET&quot;] }<br>      }<br>    },<br>    &quot;DefaultRootObject&quot;: &quot;index.html&quot;,<br>    &quot;Enabled&quot;: true,<br>    &quot;Comment&quot;: &quot;Serverless App Frontend&quot;<br>  }&#39;</pre><p>After creation (this takes 10–15 minutes to deploy globally), upload your frontend build:</p><pre># Build your frontend first (e.g., React/Vue/Angular)<br>npm run build<br><br># Upload to S3 (adjust &#39;dist&#39; to your build output folder)<br>aws s3 sync ./dist s3://your-app-frontend-assets \<br>  --delete \<br>  --cache-control &quot;public, max-age=31536000, immutable&quot;<br><br># HTML files should have shorter cache TTL<br>aws s3 cp ./dist/index.html s3://your-app-frontend-assets/index.html \<br>  --cache-control &quot;public, max-age=0, must-revalidate&quot;</pre><h3>Step 6: Add Authentication with Cognito</h3><p>No app is complete without auth. Amazon Cognito handles sign-up, login, tokens, and password reset without you writing a single line of auth code.</p><pre># Create a User Pool<br>USER_POOL_ID=$(aws cognito-idp create-user-pool \<br>  --pool-name AppUserPool \<br>  --policies &#39;PasswordPolicy={MinimumLength=8,RequireUppercase=true,RequireLowercase=true,RequireNumbers=true}&#39; \<br>  --auto-verified-attributes email \<br>  --query &#39;UserPool.Id&#39; \<br>  --output text)<br><br>echo &quot;User Pool ID: $USER_POOL_ID&quot;<br><br># Create an App Client (for your frontend to use)<br>CLIENT_ID=$(aws cognito-idp create-user-pool-client \<br>  --user-pool-id $USER_POOL_ID \<br>  --client-name AppWebClient \<br>  --no-generate-secret \<br>  --explicit-auth-flows ALLOW_USER_SRP_AUTH ALLOW_REFRESH_TOKEN_AUTH \<br>  --query &#39;UserPoolClient.ClientId&#39; \<br>  --output text)<br>echo &quot;Client ID: $CLIENT_ID&quot;</pre><p>In your frontend, use AWS Amplify to handle auth flows with just a few lines:</p><pre>import { Amplify } from &quot;aws-amplify&quot;;<br>import { signIn, signUp, confirmSignUp } from &quot;aws-amplify/auth&quot;;<br><br>Amplify.configure({<br>  Auth: {<br>    Cognito: {<br>      userPoolId: &quot;us-east-1_XXXXXXX&quot;,<br>      userPoolClientId: &quot;your-client-id&quot;,<br>    },<br>  },<br>});<br>// Sign up<br>await signUp({<br>  username: &quot;alice@example.com&quot;,<br>  password: &quot;SecurePass123!&quot;,<br>  options: { userAttributes: { email: &quot;alice@example.com&quot; } },<br>});<br>// Sign in<br>const { isSignedIn } = await signIn({<br>  username: &quot;alice@example.com&quot;,<br>  password: &quot;SecurePass123!&quot;,<br>});</pre><p>To protect Lambda routes, add a Cognito authorizer to API Gateway:</p><pre># Create the authorizer<br>AUTHORIZER_ID=$(aws apigatewayv2 create-authorizer \<br>  --api-id $API_ID \<br>  --authorizer-type JWT \<br>  --identity-source &#39;$request.header.Authorization&#39; \<br>  --name CognitoAuthorizer \<br>  --jwt-configuration \<br>    Audience=$CLIENT_ID,\<br>    Issuer=https://cognito-idp.us-east-1.amazonaws.com/$USER_POOL_ID \<br>  --query &#39;AuthorizerId&#39; \<br>  --output text)<br><br># Apply it to a route<br>aws apigatewayv2 update-route \<br>  --api-id $API_ID \<br>  --route-id YOUR_ROUTE_ID \<br>  --authorization-type JWT \<br>  --authorizer-id $AUTHORIZER_ID</pre><h3>Monitoring and Observability</h3><p>CloudWatch is automatically capturing Lambda logs, but set up a dashboard to keep an eye on things:</p><pre># View recent Lambda logs<br>aws logs tail /aws/lambda/createUser --follow<br><br># Create a CloudWatch alarm for Lambda errors<br>aws cloudwatch put-metric-alarm \<br>  --alarm-name &quot;CreateUser-Errors&quot; \<br>  --metric-name Errors \<br>  --namespace AWS/Lambda \<br>  --dimensions Name=FunctionName,Value=createUser \<br>  --statistic Sum \<br>  --period 60 \<br>  --threshold 5 \<br>  --comparison-operator GreaterThanOrEqualToThreshold \<br>  --evaluation-periods 1 \<br>  --alarm-actions arn:aws:sns:us-east-1:${ACCOUNT_ID}:your-alert-topic</pre><p>For structured logging inside Lambda, use a lightweight logger:</p><pre>const log = (level, message, data = {}) =&gt; {<br>  console.log(JSON.stringify({ level, message, timestamp: new Date().toISOString(), ...data }));<br>};<br><br>// Usage<br>log(&quot;info&quot;, &quot;User created&quot;, { userId, email });<br>log(&quot;error&quot;, &quot;DynamoDB write failed&quot;, { error: error.message });</pre><p>CloudWatch Logs Insights lets you query these logs powerfully:</p><pre>fields @timestamp, level, message, userId<br>| filter level = &quot;error&quot;<br>| sort @timestamp desc<br>| limit 20</pre><h3>Cost Breakdown at 1,000 Active Users</h3><p>Here’s a realistic monthly cost estimate for an app with 1,000 active users, assuming moderate usage (each user makes ~50 API calls/day):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bACRwhBZe3FZO3uK-UgDFw.png" /><figcaption>AI Generated Image</figcaption></figure><p>At 10,000 users, that figure scales roughly linearly around $150–200/month. Compare that to a single EC2 instance with a managed RDS database, which can easily run $100–300/month before you have a single user.</p><h3>Production Hardening Tips</h3><p>These are the details that separate a demo from a production deployment:</p><p><strong>Use environment variables for configuration.</strong> Never hardcode ARNs, table names, or secrets in your Lambda code.</p><pre>aws lambda update-function-configuration \<br>  --function-name createUser \<br>  --environment Variables=&#39;{<br>    &quot;TABLE_NAME&quot;: &quot;AppUsers&quot;,<br>    &quot;REGION&quot;: &quot;us-east-1&quot;,<br>    &quot;ENVIRONMENT&quot;: &quot;production&quot;<br>  }&#39;</pre><p><strong>Enable Lambda reserved concurrency</strong> to prevent one noisy function from starving the rest of your system:</p><pre>aws lambda put-function-concurrency \<br>  --function-name createUser \<br>  --reserved-concurrent-executions 100</pre><p><strong>Use AWS Secrets Manager for sensitive credentials</strong> (third-party API keys, database connection strings for when you outgrow DynamoDB, etc.):</p><pre>aws secretsmanager create-secret \<br>  --name prod/app/stripe-key \<br>  --secret-string &#39;{&quot;stripeSecretKey&quot;:&quot;sk_live_...&quot;}&#39;</pre><p><strong>Tag all resources</strong> for cost tracking and governance:</p><pre>aws dynamodb tag-resource \<br>  --resource-arn arn:aws:dynamodb:us-east-1:${ACCOUNT_ID}:table/AppUsers \<br>  --tags Key=Project,Value=MyApp Key=Environment,Value=production</pre><p><strong>Set up AWS Budgets</strong> to get an email before you accidentally run up a big bill:</p><pre>aws budgets create-budget \<br>  --account-id $ACCOUNT_ID \<br>  --budget &#39;{<br>    &quot;BudgetName&quot;: &quot;MonthlyAppBudget&quot;,<br>    &quot;BudgetLimit&quot;: { &quot;Amount&quot;: &quot;50&quot;, &quot;Unit&quot;: &quot;USD&quot; },<br>    &quot;TimeUnit&quot;: &quot;MONTHLY&quot;,<br>    &quot;BudgetType&quot;: &quot;COST&quot;<br>  }&#39; \<br>  --notifications-with-subscribers &#39;[{<br>    &quot;Notification&quot;: {<br>      &quot;NotificationType&quot;: &quot;ACTUAL&quot;,<br>      &quot;ComparisonOperator&quot;: &quot;GREATER_THAN&quot;,<br>      &quot;Threshold&quot;: 80<br>    },<br>    &quot;Subscribers&quot;: [{ &quot;SubscriptionType&quot;: &quot;EMAIL&quot;, &quot;Address&quot;: &quot;you@yourapp.com&quot; }]<br>  }]&#39;</pre><h3>When to Move Beyond This Architecture</h3><p>This stack handles 1,000 users with ease and can stretch to 10,000–50,000 without major changes. You’ll want to consider evolving it when:</p><ul><li><strong>Lambda cold starts become a UX problem:</strong> consider Provisioned Concurrency for latency-sensitive endpoints</li><li><strong>DynamoDB query patterns get complex:</strong> consider adding an ElasticSearch/OpenSearch layer for full-text search</li><li><strong>You need relational queries: </strong>Aurora Serverless v2 gives you PostgreSQL-compatible SQL that still scales to zero</li><li><strong>Background jobs grow:</strong> introduce SQS queues and dedicated worker Lambdas to decouple processing from API responses</li><li><strong>Real-time features are needed:</strong> API Gateway WebSocket APIs integrate cleanly with Lambda and DynamoDB Streams</li></ul><h3>Wrapping Up</h3><p>The architecture covered here, CloudFront, S3, API Gateway, Lambda, DynamoDB, and Cognito, is a legitimate production setup, not just a toy. Companies have run it on a serious scale. The combination of zero idle cost, automatic scaling, and zero infrastructure management makes it one of the most productive and economical choices for teams that want to focus on building product rather than managing servers.</p><p>The full setup covered in this article can be done in a day. The cost at 1,000 users is less than a cup of coffee per day. And when you’re ready to scale, the architecture grows with you.</p><p><em>All AWS CLI commands in this article use the </em><em>us-east-1 region. Substitute your preferred region where appropriate. Always review IAM permissions and scope them to least-privilege before going to production.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb3449f80758" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/building-a-cost-effective-serverless-architecture-on-aws-that-scales-to-1-000-users-fb3449f80758">Building a Cost-Effective Serverless Architecture on AWS That Scales to 1,000+ Users</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Architecture Explained: What It Is, How It Works, and Why It Matters]]></title>
            <link>https://awstip.com/serverless-architecture-explained-what-it-is-how-it-works-and-why-it-matters-dbda5a971b50?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbda5a971b50</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 21:43:27 GMT</pubDate>
            <atom:updated>2026-06-16T23:37:53.426Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical, AWS-focused guide for developers entering the cloud-native world</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gCU1OZDruzi_j7CJ4pHHSQ.png" /><figcaption>AI Generated Image</figcaption></figure><h3>Introduction</h3><p>Imagine you’re building a web application. Traditionally, you’d rent a server (or buy one), install an operating system, configure a runtime, deploy your code, and then spend considerable effort keeping everything running, patching the OS, scaling up when traffic spikes, and paying for compute even at 3 AM when nobody is using your app.</p><p>Serverless architecture flips this model on its head.</p><p>Despite the name, serverless doesn’t mean there are <em>no</em> servers. There are still servers, you just don’t manage them. The cloud provider handles all the infrastructure concerns, and you focus exclusively on writing business logic. You pay only for the compute time you actually consume, not for idle capacity.</p><p>This article walks through what serverless really means, how it differs from traditional software architectures, and how AWS implements it through a rich ecosystem of managed services.</p><h3>Part 1: A Brief History of Software Architectures</h3><p>To appreciate serverless, it helps to understand where we came from.</p><h3>1.1 Bare Metal and On-Premises</h3><p>In the early days of enterprise software, companies owned physical servers housed in their own data centers. Provisioning a new server could take weeks, ordering hardware, racking it, wiring it, and configuring it before a single line of code was ever deployed. Capacity planning was largely guesswork: either you over-provisioned (wasting money) or under-provisioned (risking downtime during peaks).</p><h3>1.2 Virtual Machines (VMs)</h3><p>Virtualization changed the equation. A single physical machine could be partitioned into multiple virtual machines, each with its own OS, memory allocation, and CPU slice. Cloud providers like AWS launched with this model, AWS EC2 (Elastic Compute Cloud), introduced in 2006, lets you rent virtual machines by the hour.</p><p>VMs made infrastructure far more flexible, but the operational burden remained: you still had to manage the OS, runtime, security patches, and scaling policies.</p><h3>1.3 Containers and Microservices</h3><p>Docker (2013) and Kubernetes (2014) ushered in the container era. Containers package an application and its dependencies into a portable, lightweight unit that runs consistently across environments. Microservices architectures emerged alongside containers, decomposing large monolithic applications into smaller, independently deployable services.</p><p>Containers reduced the “works on my machine” problem and improved resource efficiency versus VMs. But now developers needed to orchestrate clusters of containers, managing service discovery, load balancing, rolling deployments, and cluster health. Kubernetes is powerful, but notoriously complex.</p><h3>1.4 Serverless</h3><p>Serverless is the next step in the abstraction ladder. You write a function. You deploy it. The cloud provider runs it on demand, scales it automatically, and you pay per invocation. No servers. No OS. No containers to orchestrate.</p><p>AWS Lambda, launched in 2014, is the service that popularized this model and remains the flagship serverless compute service on AWS.</p><h3>Part 2: What Is Serverless Architecture?</h3><h3>2.1 The Core Concept: Functions as a Service (FaaS)</h3><p>At the heart of serverless is the concept of <strong>Functions as a Service (FaaS)</strong>. Rather than deploying a long-running application server, you deploy individual <em>functions</em> as small, focused units of code that execute in response to an event and then terminate.</p><p>AWS Lambda is the canonical FaaS implementation. A Lambda function:</p><ul><li>Is written in a supported runtime (Node.js, Python, Java, Go, Ruby, .NET, and more)</li><li>Is triggered by an <strong>event</strong> (an HTTP request, a file uploaded to S3, a message in a queue, a scheduled timer, etc.)</li><li>Executes, does its work, and shuts down</li><li>Scales automatically from zero invocations to thousands per second, without any configuration</li></ul><p>Here’s a minimal Python Lambda function:</p><pre>import json<br>def lambda_handler(event, context):<br>    name = event.get(&quot;name&quot;, &quot;World&quot;)<br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: json.dumps({&quot;message&quot;: f&quot;Hello, {name}!&quot;})<br>    }</pre><p>This function takes an event object, extracts a name, and returns a greeting. Lambda will run this code whenever it’s invoked, automatically provisioning compute resources to handle as many concurrent requests as needed.</p><h3>2.2 Key Characteristics of Serverless</h3><p>The Cloud Native Computing Foundation and AWS define serverless through several attributes:</p><p><strong>No server management.</strong> You never SSH into a machine, patch an OS, or configure a web server. The runtime environment is fully managed.</p><p><strong>Pay-per-use pricing.</strong> AWS Lambda charges based on the number of invocations and the duration of execution (measured in 1ms increments), combined with the memory allocated. A function that runs 1 million times for 200ms each, with 128MB of memory, costs roughly $0.42/month, a fraction of what an equivalent EC2 instance would cost.</p><p><strong>Automatic scaling.</strong> Lambda scales concurrently, not vertically. If 10,000 requests arrive simultaneously, Lambda spins up 10,000 execution environments in parallel (subject to account concurrency limits, which are configurable).</p><p><strong>Event-driven execution.</strong> Functions don’t idle. They execute when triggered and stop when done. This is a fundamental shift from the always-on model of traditional servers.</p><p><strong>Stateless by design.</strong> Each function invocation is independent. Lambda functions must treat themselves as stateless; any state that needs to persist between calls must be stored externally (in a database, cache, or object store).</p><h3>2.3 Beyond FaaS: The Broader Serverless Ecosystem</h3><p>Serverless isn’t just Lambda. AWS offers a full ecosystem of serverless-native managed services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAK4K0_6vbOrMczcNSRP1A.png" /><figcaption>AI Generated Image</figcaption></figure><p>The power of serverless on AWS comes from composing these services together. You don’t just make one function; you build an architecture where events flow through a pipeline of managed services, each handling a specific concern without any server management.</p><h3>Part 3: Serverless vs. Traditional Architectures: A Detailed Comparison</h3><h3>3.1 The Monolithic Architecture</h3><p>A monolith is a single, self-contained application where all components, the UI logic, business logic, and data access layer, are bundled together and deployed as one unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZtyiBSbVBtJBPknqct86Q.png" /><figcaption>AI Generated Image</figcaption></figure><p><strong>Strengths:</strong> Simple to develop initially, easy to test end-to-end, straightforward deployment.</p><p><strong>Weaknesses:</strong> Scaling means scaling the <em>entire</em> application, even if only one module is under load. A bug in one module can crash the whole app. Long build and deploy cycles as the codebase grows.</p><p>On AWS, monoliths typically run on <strong>EC2 instances</strong> behind an <strong>Elastic Load Balancer</strong>, with <strong>Auto Scaling Groups</strong> to handle traffic spikes. You still manage AMIs, instance types, OS patches, and scaling policies.</p><h3>3.2 The Microservices Architecture</h3><p>Microservices decompose the monolith into independently deployable services, each owning its own data and communicating over APIs or message queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIbHfE3AKbyH-pdSrS4-bg.png" /><figcaption>AI Generated Image</figcaption></figure><p>On AWS, microservices typically run on <strong>Amazon ECS</strong> (Elastic Container Service) or <strong>Amazon EKS</strong> (Elastic Kubernetes Service), using Docker containers. Each service can be scaled independently, deployed independently, and written in a different language if needed.</p><p><strong>Strengths:</strong> Independent scalability, fault isolation, team autonomy, and technology flexibility.</p><p><strong>Weaknesses:</strong> Operational complexity explodes. You now manage service meshes, container orchestration, inter-service authentication, distributed tracing, and cluster infrastructure.</p><h3>3.3 The Serverless Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BY5Yk1h3TtqYTbc-Of-Z4w.png" /><figcaption>AI Generated Image</figcaption></figure><p>Each arrow is an event trigger. Each box is a fully managed service. No infrastructure to configure. No clusters to run.</p><p><strong>Strengths:</strong> Near-zero operational overhead, true pay-per-use, infinite automatic scaling, rapid development.</p><p><strong>Weaknesses:</strong> Cold starts, execution time limits (Lambda max is 15 minutes), vendor lock-in, complex distributed tracing, and less control over the runtime environment.</p><h3>3.4 Head-to-Head Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYewGRJE_-mAkQuXMtFSpQ.png" /><figcaption>AI Generated Image</figcaption></figure><h3>Part 4: A Real-World Serverless Architecture on AWS</h3><p>Let’s walk through a practical example: a <strong>serverless image processing pipeline</strong>.</p><p><strong>Scenario:</strong> Users upload images to your app. Each image needs to be resized to multiple dimensions, have metadata extracted, and have a thumbnail stored.</p><h3>Traditional approach:</h3><ul><li>Spin up an EC2 instance running a worker process</li><li>Poll an SQS queue for new images</li><li>Resize images using ImageMagick</li><li>Store results in S3</li><li>Pay for the EC2 instance, whether it’s processing images or not</li></ul><h3>Serverless approach:</h3><p><strong>Step 1: Upload trigger.</strong></p><p>A user uploads an image to an <strong>S3 bucket</strong>. S3 automatically emits an event.</p><p><strong>Step 2: Lambda triggered by S3</strong></p><pre>import boto3<br>import json<br><br>s3 = boto3.client(&#39;s3&#39;)<br>sqs = boto3.client(&#39;sqs&#39;)<br>def lambda_handler(event, context):<br>    for record in event[&#39;Records&#39;]:<br>        bucket = record[&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>        key = record[&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]<br>        <br>        # Send to SQS for downstream processing<br>        sqs.send_message(<br>            QueueUrl=&#39;https://sqs.us-east-1.amazonaws.com/123456789/image-jobs&#39;,<br>            MessageBody=json.dumps({&#39;bucket&#39;: bucket, &#39;key&#39;: key})<br>        )<br>    <br>    return {&quot;status&quot;: &quot;queued&quot;}</pre><p><strong>Step 3: Processing Lambda reads from SQS</strong></p><p>The SQS queue triggers a second Lambda function. It downloads the image, resizes it using Pillow (packaged in a Lambda Layer), and stores the results back in S3.</p><p><strong>Step 4: EventBridge fan-out</strong></p><p>After processing, an event is emitted to <strong>EventBridge</strong>, which routes it to two separate Lambda functions: one that updates <strong>DynamoDB</strong> with image metadata, and one that sends a notification via <strong>SNS</strong>.</p><p><strong>Step 5: Step Functions for orchestration</strong> (optional)</p><p>If the workflow becomes complex with conditional branching (e.g., different processing based on image type), <strong>AWS Step Functions</strong> provides a visual state machine to orchestrate Lambda invocations, with built-in error handling and retries.</p><p>This entire architecture processes zero images and costs essentially nothing when no uploads are happening, and automatically handles 10,000 simultaneous uploads without any configuration change.</p><h3>Part 5: Key Concepts Every Serverless Developer Should Know</h3><h3>5.1 Cold Starts</h3><p>When a Lambda function hasn’t been invoked recently, AWS needs to provision a new execution environment, downloading your code, initializing the runtime, and running your initialization code. This is called a <strong>cold start</strong>, and it adds latency (typically 100ms–1s, though Java and .NET can be higher).</p><p><strong>Mitigations:</strong></p><ul><li>Use <strong>Provisioned Concurrency:</strong> Lambda keeps a set number of environments pre-warmed and ready to serve requests instantly (at a cost)</li><li>Choose faster runtimes (Python, Node.js) over heavier ones (Java) for latency-sensitive paths</li><li>Keep Lambda packages small: smaller deployment packages initialize faster</li><li>Use <strong>Lambda SnapStart</strong> (for Java): AWS snapshots a post-initialization execution environment for near-instant startup</li></ul><h3>5.2 Lambda Execution Model</h3><p>Lambda functions run inside isolated <strong>micro-VMs</strong> powered by AWS Firecracker (an open-source virtualization technology built by AWS). Each execution environment processes one request at a time.</p><p>Concurrency = number of execution environments running simultaneously.</p><p>Key limits to know:</p><ul><li><strong>Default concurrency limit:</strong> 1,000 concurrent executions per region (can be increased via support request)</li><li><strong>Maximum execution duration:</strong> 15 minutes</li><li><strong>Maximum deployment package size:</strong> 50MB (zipped), 250MB unzipped</li><li><strong>Ephemeral storage:</strong> 512MB–10GB of /tmp storage per invocation</li></ul><h3>5.3 Event Sources and Triggers</h3><p>Lambda integrates natively with dozens of AWS services. Common event sources include:</p><ul><li><strong>Amazon API Gateway / ALB</strong>: HTTP requests</li><li><strong>Amazon S3: </strong>Object created/deleted events</li><li><strong>Amazon SQS: </strong>Messages in a queue (Lambda polls the queue)</li><li><strong>Amazon DynamoDB Streams: </strong>Record changes in a DynamoDB table</li><li><strong>Amazon Kinesis: </strong>Real-time data streams</li><li><strong>Amazon EventBridge: </strong>Custom events and scheduled rules (cron jobs)</li><li><strong>Amazon SNS: </strong>Push notifications</li><li><strong>AWS IoT: </strong>Device events</li></ul><h3>5.4 Serverless Databases</h3><p>Serverless compute needs serverless storage. AWS offers two primary options:</p><p><strong>Amazon DynamoDB</strong> is a fully managed NoSQL key-value and document database. It offers single-digit millisecond performance at any scale, automatic multi-AZ replication, and an <strong>on-demand capacity mode</strong> that charges per request, perfectly aligned with the Lambda pricing model. DynamoDB Streams also serves as a native event source for Lambda.</p><p><strong>Amazon Aurora Serverless v2</strong> is a relational database that automatically scales capacity up or down based on demand, in increments as small as 0.5 ACUs (Aurora Capacity Units). It’s a strong choice when you need SQL semantics (joins, transactions, complex queries) in a serverless architecture, though it has a minimum cost even when idle.</p><h3>5.5 Infrastructure as Code</h3><p>Managing serverless architectures manually through the AWS Console doesn’t scale. Use infrastructure as code (IaC) to define and deploy your resources.</p><p>Popular options for serverless:</p><ul><li><strong>AWS SAM (Serverless Application Model)</strong></li></ul><p>AWS’s own open-source framework that extends CloudFormation with shorthand syntax specifically for Lambda, API Gateway, and DynamoDB. The sam deploy command builds and deploys your stack.</p><ul><li><strong>Serverless Framework</strong></li></ul><p>A popular open-source framework with multi-cloud support and a large plugin ecosystem</p><ul><li><strong>AWS CDK (Cloud Development Kit)</strong></li></ul><p>Define infrastructure using familiar programming languages (TypeScript, Python, Java) and synthesize to CloudFormation</p><p>A basic SAM template for a REST API backed by Lambda looks like this:</p><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Transform: AWS::Serverless-2016-10-31<br><br>Globals:<br>  Function:<br>    Runtime: python3.12<br>    Timeout: 10<br>    MemorySize: 256<br>Resources:<br>  GetOrdersFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      CodeUri: src/<br>      Handler: orders.get_handler<br>      Events:<br>        GetOrders:<br>          Type: Api<br>          Properties:<br>            Path: /orders<br>            Method: GET<br>      Policies:<br>        - DynamoDBReadPolicy:<br>            TableName: !Ref OrdersTable<br>  OrdersTable:<br>    Type: AWS::Serverless::SimpleTable<br>    Properties:<br>      PrimaryKey:<br>        Name: orderId<br>        Type: String</pre><p>With sam deploy, this provisions a Lambda function, an API Gateway endpoint, and a DynamoDB table fully linked and secured with IAM in minutes.</p><h3>Part 6: When to Use Serverless (and When Not To)</h3><h3>Serverless is a great fit when:</h3><ul><li><strong>Traffic is unpredictable or spiky:</strong> e-commerce flash sales, scheduled batch jobs, webhooks</li><li><strong>The workload is event-driven: </strong>processing files on upload, reacting to database changes, handling async tasks</li><li><strong>You want to minimize operational overhead: </strong>early-stage startups, small teams, prototype-to-production paths</li><li><strong>Cost at low scale matters: </strong>a side project that gets 10,000 requests/month costs cents on Lambda vs. ~$15–30/month for the cheapest EC2 instance</li></ul><h3>Serverless may not be ideal when:</h3><ul><li><strong>Sustained, predictable high throughput is needed: </strong>if your Lambda runs 24/7 under constant load, a reserved EC2 instance or container cluster may be cheaper</li><li><strong>Execution time exceeds 15 minutes: </strong>use AWS Fargate (serverless containers) or EC2 for long-running batch jobs</li><li><strong>You need low-latency p99 performance: </strong>cold starts introduce tail latency; gaming backends and HFT systems may need always-warm compute</li><li><strong>Complex stateful processing: </strong>workflows with heavy in-memory state are awkward to fit into the stateless Lambda model</li></ul><h3>Part 7: Observability in Serverless</h3><p>Serverless architectures are inherently distributed, which makes debugging and monitoring more challenging than traditional apps.</p><p><strong>Amazon CloudWatch</strong> is the default observability service on AWS. Lambda automatically emits logs to CloudWatch Logs and publishes metrics like invocation count, duration, error rate, and throttles to CloudWatch Metrics.</p><p><strong>AWS X-Ray</strong> provides distributed tracing across Lambda functions, API Gateway, DynamoDB, and other services essential for understanding where latency is coming from in a chain of function invocations.</p><p><strong>AWS Lambda Power Tuning</strong> (an open-source Step Functions state machine) helps you find the optimal memory configuration for your functions. More memory also means more CPU, so the right setting balances cost and speed.</p><p>Third-party tools like <strong>Datadog</strong>, <strong>Lumigo</strong>, and <strong>Thundra</strong> offer enhanced serverless observability with richer tracing, anomaly detection, and cost analytics built specifically for Lambda environments.</p><h3>Conclusion</h3><p>Serverless architecture represents a genuine shift in how we think about building and operating software. Abstracting away all infrastructure concerns, it lets developers focus on what matters: delivering business value through code.</p><p>The serverless model, epitomized by AWS Lambda and its surrounding ecosystem, excels at event-driven, variable-load workloads where operational simplicity and cost efficiency are priorities. It’s not a silver bullet: cold starts, execution limits, and vendor lock-in are real trade-offs. But for a rapidly growing class of applications, serverless is not just viable, it’s the superior choice.</p><p>The abstraction journey from bare metal → VMs → containers → serverless is one of progressive simplification, each step offloading more operational responsibility to the platform. Serverless sits at the top of that ladder today. Understanding where it fits and where it doesn’t is a critical skill for any modern cloud engineer.</p><h3>References</h3><ol><li><strong>AWS Lambda Developer Guide:</strong> Official documentation for AWS Lambda, including runtime support, concurrency model, execution limits, and pricing. <a href="https://docs.aws.amazon.com/lambda/latest/dg/welcome.html">https://docs.aws.amazon.com/lambda/latest/dg/welcome.html</a></li><li><strong>AWS Serverless Application Model (SAM) Documentation: </strong>Official guide for the SAM framework, including template syntax and CLI reference. <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html">https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html</a></li><li><strong>Amazon DynamoDB Developer Guide: </strong>Covers on-demand capacity, DynamoDB Streams, and integration with Lambda. <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html">https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html</a></li><li><strong>AWS Step Functions Developer Guide: </strong>Serverless workflow orchestration for coordinating Lambda functions. <a href="https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html">https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html</a></li><li><strong>Firecracker: Lightweight Virtualization for Serverless Applications: </strong>AWS research paper describing the MicroVM technology powering Lambda. <a href="https://www.usenix.org/conference/nsdi20/presentation/agache">https://www.usenix.org/conference/nsdi20/presentation/agache</a></li><li><strong>Yan Cui (theburningmonk.com) “Serverless Architectural Patterns”: </strong>Practical patterns and anti-patterns for building production serverless systems on AWS. <a href="https://theburningmonk.com/">https://theburningmonk.com/</a></li><li><strong>AWS Well-Architected Framework Serverless Lens: </strong>AWS guidance on applying the Well-Architected principles (operational excellence, security, reliability, performance efficiency, cost optimization) specifically to serverless workloads. <a href="https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/welcome.html">https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/welcome.html</a></li><li><strong>CNCF Serverless Whitepaper v1.0:</strong> Cloud Native Computing Foundation’s foundational document defining serverless computing characteristics. <a href="https://github.com/cncf/wg-serverless/blob/master/whitepapers/serverless-overview/cncf_serverless_whitepaper_v1.0.pdf">https://github.com/cncf/wg-serverless/blob/master/whitepapers/serverless-overview/cncf_serverless_whitepaper_v1.0.pdf</a></li><li><strong>Amazon Aurora Serverless v2 Documentation:</strong> Covers auto-scaling relational database behavior and ACU capacity model. <a href="https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2.html">https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2.html</a></li><li><strong>AWS re:Invent 2023 “Optimizing AWS Lambda” (SVS401):</strong> Deep dive session on Lambda performance tuning, cold starts, and Provisioned Concurrency best practices. <a href="https://www.youtube.com/results?search_query=AWS+reInvent+Lambda+optimization+SVS401">https://www.youtube.com/results?search_query=AWS+reInvent+Lambda+optimization+SVS401</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbda5a971b50" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/serverless-architecture-explained-what-it-is-how-it-works-and-why-it-matters-dbda5a971b50">Serverless Architecture Explained: What It Is, How It Works, and Why It Matters</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You’re Probably Overpaying for DynamoDB. Here’s How to Fix It.]]></title>
            <link>https://awstip.com/youre-probably-overpaying-for-dynamodb-here-s-how-to-fix-it-5e29a37b3c69?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e29a37b3c69</guid>
            <category><![CDATA[aws-cost-optimization]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 02:23:00 GMT</pubDate>
            <atom:updated>2026-06-16T23:38:26.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-58kGNPIoYzP0COzcBQgQ.png" /><figcaption>AI Generated Image</figcaption></figure><p>DynamoDB is one of those services that feels free until it suddenly isn’t. You spin up a table, start writing data, and everything looks great in development. Then you hit production, traffic picks up, and your AWS bill has a line item you weren’t expecting.</p><p>The good news is that most DynamoDB cost problems are predictable and fixable. This article walks through the main reasons teams overspend on DynamoDB and what you can actually do about it.</p><h3>First, understand how DynamoDB charges you</h3><p>Before you can optimize anything, you need to know what the bill is made of. DynamoDB charges you for three things:</p><p><strong>Read and write requests.</strong> Every time you read or write data, DynamoDB counts it. Reads are measured in Read Capacity Units (RCUs) and writes in Write Capacity Units (WCUs). One RCU lets you read up to 4KB of data. One WCU lets you write up to 1KB.</p><p><strong>Storage.</strong> You pay per GB for the data sitting in your table, including indexes.</p><p><strong>Additional features.</strong> Things like backups, streams, and global tables add to the bill.</p><p>Most of the time, request costs are where the real money goes. That’s where we’ll focus.</p><h3>On-demand vs. provisioned capacity: pick the right one</h3><p>When you create a DynamoDB table, you choose a capacity mode. This is one of the first decisions that affects your bill, and a lot of beginners default to on-demand without thinking about it.</p><p><strong>On-demand mode</strong> charges you per request. No planning required, scales automatically. Great for unpredictable workloads or early-stage products where traffic is sporadic.</p><p><strong>Provisioned capacity</strong> lets you reserve a set number of RCUs and WCUs per second at a lower per-unit price. If your traffic is consistent or predictable, provisioned is almost always cheaper.</p><p>Here’s a rough rule of thumb: if you can predict your traffic patterns and your table gets consistent use throughout the day, provisioned capacity will cost you less. If your workload is bursty or you have no idea what traffic looks like yet, start with on-demand.</p><p>You can also enable <strong>auto scaling</strong> on provisioned tables to let AWS adjust capacity up and down based on actual usage. This gives you something close to the flexibility of on-demand at provisioned prices.</p><h3>Stop doing full table scans</h3><p>This one hurts the most and is the easiest to miss when you’re starting out.</p><p>A Scan operation in DynamoDB reads every single item in your table. Every item. If your table has 10 million rows and you only need 50 results, you still get charged for reading all 10 million rows worth of data.</p><p>In contrast, a Query operation reads only the items that match your partition key (and optionally your sort key). It&#39;s targeted, it&#39;s efficient, and it costs a fraction of a scan.</p><p>The fix is to design your table with your access patterns in mind before you write the first item. Ask yourself: what queries will my application actually run? Make sure your partition key and sort key support those queries directly.</p><p>If you’re already running scans in production and can’t refactor immediately, at least use FilterExpression to reduce the data you return to the client, and use Limit to cap how many items DynamoDB evaluates per request. These won&#39;t reduce the read cost of the scan itself, but they reduce the load on your application.</p><h3>Be careful with Global Secondary Indexes</h3><p>Global Secondary Indexes (GSIs) are powerful. They let you query your table on attributes other than the primary key. But they come with a real cost: every write to your base table that touches an indexed attribute also writes to the GSI. That doubles (or triples, depending on how many GSIs you have) your write costs.</p><p>A few things to keep in mind:</p><ul><li>Only index attributes you actually query on. A GSI on a column you query once a month is not worth it.</li><li>Project only the attributes you need into the GSI. By default, you can choose to project all attributes, only keys, or a specific set. Projecting all attributes is convenient, but it increases storage and read costs.</li><li>Audit your GSIs periodically. Tables accumulate indexes over time as requirements change. Old indexes that no longer serve a query pattern are pure waste.</li></ul><h3>Use the right consistency level for reads</h3><p>DynamoDB gives you two options for reads: eventually consistent and strongly consistent.</p><p>Eventually, consistent reads use half an RCU per 4KB of data. Strongly consistent reads use a full RCU. That’s a 2x cost difference.</p><p>Strongly consistent reads guarantee you get the latest version of an item. Eventually, consistent reads might return data that’s a few hundred milliseconds behind.</p><p>For most read operations, eventual consistency is fine. Leaderboards, product catalogs, user profiles, and activity feeds are usually fine with eventual consistency. You only need strong consistency when your application logic depends on reading the exact latest write, like in financial transactions or inventory management.</p><p>Check your code and see how many of your reads are using ConsistentRead: true. If it&#39;s a habit you&#39;ve picked up without thinking about it, switching to eventual consistency where it&#39;s safe could cut your read costs in half.</p><h3>Compress and right-size your items</h3><p>DynamoDB charges by the amount of data transferred in each request, rounded up to the nearest KB. Large items cost more to read and write.</p><p>A few habits that help:</p><ul><li>Use short attribute names. ts instead of timestamp, uid instead of userId. It sounds minor, but attribute names are stored and billed along with the data.</li><li>Store only what you need. Don’t write a full JSON blob of a third-party API response if you only need three fields from it.</li><li>Compress large values. If you’re storing big text or binary blobs, compress them before writing to DynamoDB and decompress after reading.</li></ul><p>Aim to keep items small. If an item is getting close to 400KB (the max), that’s usually a sign it’s doing too much and should be restructured.</p><h3>Enable TTL for data you don’t need forever</h3><p>DynamoDB’s Time to Live (TTL) feature lets you set an expiration timestamp on items. When the timestamp passes, DynamoDB deletes the item automatically, at no charge.</p><p>This is a free cleanup. Session data, temporary tokens, cache entries, log events — anything with a natural expiration date should have a TTL set. Keeping expired data in your table costs you in storage fees every month.</p><p>Enabling TTL is a one-time setting on your table. You add a TTL attribute to your items (a Unix epoch timestamp), tell DynamoDB which attribute to use, and it handles the rest.</p><h3>Watch your backup costs</h3><p>DynamoDB offers two backup options: on-demand backups and point-in-time recovery (PITR).</p><p>PITR is convenient. It continuously backs up your table and lets you restore to any second within the last 35 days. But it’s not free. It charges you based on the size of your table.</p><p>If you have large tables and PITR turned on, check whether you actually need 35 days of recovery window. For some tables, weekly on-demand backups are more than enough and significantly cheaper. And old on-demand backups that you no longer need should be deleted — they accrue storage costs indefinitely until you remove them.</p><h3>Use AWS Cost Explorer and CloudWatch to actually see what’s happening</h3><p>None of this optimization work matters if you don’t know which tables are driving costs. AWS Cost Explorer lets you break down DynamoDB spend by table. CloudWatch metrics show you consumed RCUs, WCUs, and throttled requests in real time.</p><p>Set up a CloudWatch alarm for consumed capacity, so you get notified before costs spiral. Tag your DynamoDB tables by environment and team so you can attribute costs accurately when reviewing the bill.</p><p>Cost optimization isn’t a one-time task. It’s a habit of regularly checking what you’re spending and why.</p><h3>Single table design: the architecture that makes all of this easier</h3><p>A lot of the cost problems described in this article get worse when you model your data the way you would in a relational database — one table per entity, foreign keys everywhere, joins at query time. DynamoDB doesn’t have joins, so people reach for GSIs and scan operations to compensate. That’s where the bill starts climbing.</p><p>Single table design is a different approach. Instead of spreading your data across multiple tables, you store all your entities in one table and use a combination of partition keys, sort keys, and prefixes to separate them. A User, an Order, and an OrderItem can all live in the same table, each retrievable with a targeted Query instead of a cross-table scan.</p><p>From a cost perspective, this matters for a few reasons. Fewer tables means fewer GSIs overall, since you design your indexes around a consolidated set of access patterns from the start. Queries stay targeted. And you avoid the overhead of coordinating reads across multiple tables in your application code.</p><p>It’s a pattern that takes some getting used to, but once it clicks, it changes how you think about DynamoDB entirely. If you want a solid introduction to how it works and when to use it, this article breaks it down well: <a href="https://medium.com/aws-tip/the-single-table-pattern-in-dynamodb-a-game-changer-for-your-aws-applications-6ddd0bb75ab9">The Single Table Pattern in DynamoDB: A Game Changer for Your AWS Applications</a>.</p><h3>The short version</h3><p>DynamoDB is designed to scale, but that scalability works in both directions. It can scale your costs just as fast as it scales your performance if you’re not paying attention.</p><p>The biggest wins, in rough order of impact: switch to provisioned capacity if your traffic is predictable, stop doing table scans, prune unused indexes, switch to eventual consistency where it’s safe, and enable TTL on data with a natural expiration. Do those five things, and most teams see a meaningful reduction in their DynamoDB bill without sacrificing anything in their application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e29a37b3c69" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/youre-probably-overpaying-for-dynamodb-here-s-how-to-fix-it-5e29a37b3c69">You’re Probably Overpaying for DynamoDB. Here’s How to Fix It.</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Single Table Pattern in DynamoDB: A Game-Changer for Your AWS Applications]]></title>
            <link>https://awstip.com/the-single-table-pattern-in-dynamodb-a-game-changer-for-your-aws-applications-6ddd0bb75ab9?source=rss-4efa33817c52------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ddd0bb75ab9</guid>
            <category><![CDATA[single-table-design]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <dc:creator><![CDATA[Kaveesh Karunarathna]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 23:13:22 GMT</pubDate>
            <atom:updated>2026-06-16T23:39:13.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5JEsKMtoMmXrLE-XAoTNw.png" /><figcaption>AI Generated Image</figcaption></figure><p>When I first heard about storing multiple entity types in a single DynamoDB table, my immediate reaction was: “That sounds like a terrible idea.” Coming from a relational database background, the concept felt wrong, almost bizarre. But after implementing it in production applications, I’ve become a believer.</p><p>At <a href="https://www.axis-tech.co/">Axis Tech</a>, we use this pattern extensively across our AWS-based solutions, and it has consistently delivered better performance and lower costs. Here’s why the single table pattern might transform how you build on AWS.</p><h3>The Relational Database Mindset</h3><p>If you’re like most developers, you probably learned database design with relational databases. You normalize your data, create separate tables for users, orders, products, and reviews, then JOIN them together when needed. This approach works beautifully for traditional databases, but DynamoDB isn’t a traditional database.</p><p>DynamoDB is a NoSQL database designed for massive scale and consistent single-digit millisecond performance. It achieves this by making different trade-offs than relational databases. The biggest one? No JOINs.</p><h3>The Problem with Multiple Tables</h3><p>Let’s say you’re building an e-commerce application. Your natural instinct might be to create separate DynamoDB tables:</p><ul><li>Users table</li><li>Orders table</li><li>Products table</li><li>Reviews table</li></ul><p>This seems logical. But here’s where things get expensive and slow.</p><p><strong>Scenario:</strong> Display a user’s profile with their recent orders and product details.</p><p>With multiple tables, you need to:</p><ol><li>Query the Users table</li><li>Query the Orders table for that user&#39;s orders</li><li>Query the Products table for each product in those orders</li><li>Query the Reviews table for reviews by that user</li></ol><p>That’s potentially dozens of separate API calls to DynamoDB. Each call has latency (even if it’s just a few milliseconds), and more importantly, each call costs money. DynamoDB charges per request.</p><h3>Enter the Single Table Pattern</h3><p>The single table pattern flips this approach on its head. Instead of multiple tables, you store all your entity types in one table with a clever key design. Let me show you how it works.</p><h3>The Key Structure</h3><p>A single table uses two main attributes:</p><ul><li><strong>PK (Partition Key)</strong>: Groups related items together</li><li><strong>SK (Sort Key)</strong>: Provides ordering and enables range queries</li></ul><p>Here’s what our e-commerce data might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAsbHCdm0UvcRuCUDHDfpw.png" /><figcaption>AI Generated Image</figcaption></figure><p>Notice how we’re using composite keys. The # symbol is just a delimiter convention (it helps us visually separate the entity type from the ID).</p><h3>The Magic: One Query to Rule Them All</h3><p>Now, when you need to display Alice’s profile with her orders and reviews, you do:</p><pre>const params = {<br>  TableName: &#39;EcommerceTable&#39;,<br>  KeyConditionExpression: &#39;PK = :pk&#39;,<br>  ExpressionAttributeValues: {<br>    &#39;:pk&#39;: &#39;USER#alice123&#39;<br>  }<br>};<br><br>const result = await dynamodb.query(params);</pre><p><strong>One query.</strong> One API call. You get back all of Alice’s data (her profile, all her orders, and all her reviews) in a single request.</p><h3>Real-World Benefits</h3><h3>1. Cost Reduction</h3><p>With the multi-table approach, loading a user dashboard might require 10–20 separate queries. With single table design, it’s often just one or two. At scale, this translates to significant cost savings.</p><p>I’ve seen an application that was making 50 million requests per day to DynamoDB. After migrating to a single table pattern, they reduced that to 12 million requests (a 76% reduction). The monthly AWS bill dropped by thousands of dollars.</p><h3>2. Performance Improvements</h3><p>Fewer network round-trip means lower latency. Instead of waiting for multiple queries to complete (even in parallel), you’re waiting for one. The difference is noticeable.</p><p>Before: 150ms average response time (5 parallel queries at 30ms each) After: 35ms average response time (1 query)</p><h3>3. Simpler Application Code</h3><p>Counterintuitively, single table design often leads to cleaner code. Instead of managing multiple table configurations and query patterns, you have one well-designed access pattern.</p><pre>// Before: Multiple calls<br>const user = await getUserById(userId);<br>const orders = await getOrdersByUserId(userId);<br>const reviews = await getReviewsByUserId(userId);<br><br>// After: One call<br>const userData = await getUserData(userId);<br>// userData contains profile, orders, and reviews</pre><h3>Common Access Patterns</h3><p>Let me show you how to handle typical queries with single table design.</p><h3>Pattern 1: Get All Items for an Entity</h3><p><strong>Query:</strong> Get user profile and all related data</p><pre>{<br>  PK: &#39;USER#alice123&#39;,<br>  SK: begins_with(&#39;&#39;) // Gets everything<br>}</pre><h3>Pattern 2: Get Specific Related Items</h3><p><strong>Query:</strong> Get only a user’s orders</p><pre>{<br>  PK: &#39;USER#alice123&#39;,<br>  SK: begins_with(&#39;ORDER#&#39;)<br>}</pre><h3>Pattern 3: Get Items Within a Range</h3><p><strong>Query:</strong> Get orders from January 2024</p><pre>{<br>  PK: &#39;USER#alice123&#39;,<br>  SK: between(&#39;ORDER#2024-01-01&#39;, &#39;ORDER#2024-01-31&#39;)<br>}</pre><h3>Pattern 4: Reverse Lookups with GSI</h3><p><strong>Query:</strong> Get all reviews for a product</p><p>This requires a Global Secondary Index (GSI):</p><pre>GSI1PK: PRODUCT#prod-789<br>GSI1SK: REVIEW#alice123</pre><p>Now you can query:</p><pre>{<br>  IndexName: &#39;GSI1&#39;,<br>  KeyConditionExpression: &#39;GSI1PK = :pk&#39;,<br>  ExpressionAttributeValues: {<br>    &#39;:pk&#39;: &#39;PRODUCT#prod-789&#39;<br>  }<br>}</pre><h3>When to Use Single Table Design</h3><p>Single table pattern shines when:</p><ul><li><strong>You have clear access patterns</strong>: You know how your application will query data</li><li><strong>You need predictable performance</strong>: Single-digit millisecond latency matters</li><li><strong>You’re optimizing for cost</strong>: You want to minimize DynamoDB requests</li><li><strong>Your data is hierarchical</strong>: Entities have clear parent-child relationships</li></ul><p>It’s less ideal when:</p><ul><li><strong>Access patterns are unpredictable</strong>: Ad-hoc querying is a primary use case</li><li><strong>You need complex analytics</strong>: Reporting across multiple entity types</li><li><strong>Your team lacks NoSQL experience</strong>: There’s a learning curve</li></ul><h3>Common Pitfalls and How to Avoid Them</h3><h3>Pitfall 1: Not Planning Access Patterns</h3><p><strong>The mistake:</strong> Designing your key schema before understanding how you’ll query data.</p><p><strong>The solution:</strong> Start with your access patterns. List every query your application needs to make, then design your keys to support those patterns efficiently.</p><h3>Pitfall 2: Over-Normalizing</h3><p><strong>The mistake:</strong> Trying to avoid data duplication at all costs.</p><p><strong>The solution:</strong> Embrace strategic duplication. In NoSQL, it’s often better to duplicate data than to make multiple queries. Store the product name with the order instead of just the product ID.</p><h3>Pitfall 3: Ignoring Item Size Limits</h3><p><strong>The mistake:</strong> Storing too much data in a single item.</p><p><strong>The solution:</strong> DynamoDB has a 400KB item size limit. For large attributes (like product descriptions or review text), consider storing them separately or using S3 with a reference.</p><h3>Pitfall 4: Not Using GSIs Effectively</h3><p><strong>The mistake:</strong> Creating too many or too few GSIs.</p><p><strong>The solution:</strong> DynamoDB allows up to 20 GSIs per table. Use them strategically for reverse lookups and alternative access patterns. But remember: each GSI doubles your write costs.</p><h3>Migration Strategy</h3><p>If you’re thinking about migrating from multiple tables to single table design, here’s an approach that worked for me:</p><ol><li><strong>Document current access patterns</strong>: List every query your application makes</li><li><strong>Design your key schema</strong>: Map access patterns to PK/SK combinations</li><li><strong>Create GSIs for reverse lookups</strong>: Identify queries that need alternative access</li><li><strong>Write data transformation code</strong>: Convert existing data to the new schema</li><li><strong>Build an adapter layer</strong>: Allow old and new schemas to coexist temporarily</li><li><strong>Migrate incrementally</strong>: Move one feature at a time, not everything at once</li><li><strong>Monitor and optimize</strong>: Watch query patterns and adjust GSIs as needed</li></ol><h3>A Practical Example: Building a Social Media Feed</h3><p>Let me walk through a complete example. We’re building a simple social media app where users create posts, like posts, and follow other users.</p><h3>Access Patterns</h3><ol><li>Get user profile and their posts</li><li>Get a specific post with its likes</li><li>Get users that a person follows</li><li>Get a user’s followers</li><li>Get a feed of posts from users you follow</li></ol><h3>Table Schema</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pgZevIYDr9m4t7cXADcDg.png" /><figcaption>AI Generated Image</figcaption></figure><p><strong>Get Alice’s profile and posts:</strong></p><pre>query({<br>  PK: &#39;USER#alice&#39;,<br>  SK: begins_with(&#39;&#39;)<br>})</pre><p><strong>Get post with likes:</strong></p><pre>query({<br>  IndexName: &#39;GSI1&#39;,<br>  GSI1PK: &#39;POST#post-789&#39;<br>})<br>// Returns the post and all likes</pre><p><strong>Get users Alice follows:</strong></p><pre>query({<br>  PK: &#39;USER#alice&#39;,<br>  SK: begins_with(&#39;FOLLOWS#&#39;)<br>})</pre><p><strong>Get Alice’s followers:</strong></p><pre>query({<br>  IndexName: &#39;GSI1&#39;,<br>  GSI1PK: &#39;USER#alice&#39;,<br>  GSI1SK: begins_with(&#39;FOLLOWER#&#39;)<br>})</pre><p><strong>Get feed (posts from users Alice follows):</strong> This one’s tricky and requires two queries:</p><pre>// First, get users Alice follows<br>const follows = await query({<br>  PK: &#39;USER#alice&#39;,<br>  SK: begins_with(&#39;FOLLOWS#&#39;)<br>});<br><br>// Then batch get recent posts from those users<br>const posts = await batchGet(<br>  follows.map(f =&gt; ({<br>    PK: f.SK, // This is USER#bob format<br>    SK: begins_with(&#39;POST#&#39;)<br>  }))<br>);</pre><p>For a high-traffic feed, you might maintain a denormalized FEED items that duplicate posts for each follower, trading storage for query performance.</p><h3>Advanced Patterns: Time-Series Data</h3><p>Single table design works exceptionally well for time-series data. Let’s say you’re tracking IoT sensor readings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GZFWrXXs-6L5WDJyl8_ig.png" /><figcaption>AI Generated Image</figcaption></figure><p>Query recent readings:</p><pre>query({<br>  PK: &#39;SENSOR#temp-101&#39;,<br>  SK: between(&#39;2024-02-13T10:00:00Z&#39;, &#39;2024-02-13T10:59:59Z&#39;)<br>})</pre><p>This pattern allows you to efficiently query ranges of time-series data with single-digit millisecond latency.</p><h3>Tools and Resources</h3><h3>AWS DynamoDB Toolbox</h3><p>The <a href="https://github.com/jeremydaly/dynamodb-toolbox">DynamoDB Toolbox</a> library makes single table design easier:</p><pre>const { Table, Entity } = require(&#39;dynamodb-toolbox&#39;);<br><br>const MyTable = new Table({<br>  name: &#39;EcommerceTable&#39;,<br>  partitionKey: &#39;PK&#39;,<br>  sortKey: &#39;SK&#39;,<br>});<br>const User = new Entity({<br>  name: &#39;User&#39;,<br>  attributes: {<br>    PK: { partitionKey: true, default: (data) =&gt; `USER#${data.userId}` },<br>    SK: { sortKey: true, default: &#39;PROFILE&#39; },<br>    userId: { type: &#39;string&#39;, required: true },<br>    name: { type: &#39;string&#39; },<br>    email: { type: &#39;string&#39; }<br>  },<br>  table: MyTable<br>});</pre><h3>NoSQL Workbench</h3><p>AWS provides <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/workbench.html">NoSQL Workbench</a>, a visual tool for designing and testing your single table schema. It helps you:</p><ul><li>Model your data visually</li><li>Test access patterns</li><li>Generate sample data</li><li>Visualize query results</li></ul><h3>Alex DeBrie’s Resources</h3><p><a href="https://www.dynamodbbook.com/">Alex DeBrie’s DynamoDB Book</a> is the definitive resource on single table design. He also maintains excellent blog posts and AWS workshops on the topic.</p><h3>Final Thoughts</h3><p>The single table pattern represents a fundamental shift in thinking about data modeling. It prioritizes query efficiency and cost over the traditional relational database goals of normalization and flexibility.</p><p>Is it harder to learn than relational design? Initially, yes. Does it require more upfront planning? Absolutely. But when implemented correctly, single table design delivers:</p><ul><li><strong>Faster queries</strong>: One request instead of many</li><li><strong>Lower costs</strong>: Fewer DynamoDB operations</li><li><strong>Better scalability</strong>: Predictable performance at any scale</li><li><strong>Simpler maintenance</strong>: One table to manage and monitor</li></ul><p>Start small. Pick one feature in your application and try modeling it with single table design. Document your access patterns, experiment with key schemas, and test your queries. You might be surprised at how much better your application performs.</p><p>The single table pattern isn’t just a DynamoDB optimization technique. It’s a different way of thinking about data that can transform how you build on AWS.</p><p><em>Have you implemented single table design in your applications? What challenges did you face? Share your experiences in the comments below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ddd0bb75ab9" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/the-single-table-pattern-in-dynamodb-a-game-changer-for-your-aws-applications-6ddd0bb75ab9">The Single Table Pattern in DynamoDB: A Game-Changer for Your AWS Applications</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>