or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

aws-sdk-integration.mdbase64.mddynamodb.mdenvironment-variables.mdindex.mdlru-cache.mdmiddy-integration.mdtype-utilities.mdutility-class.md
tile.json

utility-class.mddocs/

Base Utility Class

Base class that other Powertools for AWS Lambda utilities can extend to inherit shared logic, primarily for cold start detection and heuristics. The cold start concept refers to the Lambda initialization phase where AWS creates or unfreezes an execution environment.

Capabilities

Utility Class

Base class providing cold start detection for Lambda function executions.

/**
 * Base class for Powertools utilities with cold start heuristic logic.
 *
 * Cold start refers to the Lambda 'Init' phase where AWS creates or unfreezes
 * an execution environment with configured resources, downloads code and layers,
 * initializes extensions and runtime, and runs initialization code.
 *
 * The Init phase happens either during the first invocation or in advance
 * if provisioned concurrency is enabled.
 */
class Utility {
  /**
   * Create a new Utility instance.
   * The constructor determines the initialization type and sets initial cold start status.
   */
  constructor();

  /**
   * Get the cold start status of the current execution environment.
   * Returns true during the first invocation in an execution environment,
   * false for subsequent invocations.
   *
   * The method also flips the cold start status to false after the first invocation.
   *
   * @returns Boolean indicating if this is a cold start invocation
   */
  protected getColdStart(): boolean;

  /**
   * Get the value of the AWS_LAMBDA_INITIALIZATION_TYPE environment variable.
   *
   * @returns The initialization type: 'on-demand', 'provisioned-concurrency', or 'unknown'
   */
  protected getInitializationType():
    | 'on-demand'
    | 'provisioned-concurrency'
    | 'unknown';

  /**
   * Validate that the service name provided is valid.
   * Used internally during initialization.
   *
   * @param serviceName - Service name to validate
   * @returns Boolean indicating if service name is valid (non-empty string)
   */
  protected isValidServiceName(serviceName?: string): boolean;

  /** Default service name used when none is provided */
  protected readonly defaultServiceName: string;

  /** Internal cold start tracking flag */
  protected coldStart: boolean;
}

Powertools Version Constant

/**
 * The current version of the Powertools for AWS Lambda package.
 * This is an auto-generated constant representing the package version.
 */
const PT_VERSION: string;

Usage Examples

Extending the Utility Class

import { Utility } from '@aws-lambda-powertools/commons';

class MyCustomUtility extends Utility {
  constructor() {
    super();
  }

  public logColdStart(): void {
    if (this.getColdStart()) {
      console.log('This is a cold start!');
    } else {
      console.log('This is a warm start');
    }
  }
}

// Instantiate outside the handler (module scope)
const utility = new MyCustomUtility();

export const handler = async (event: unknown, context: unknown) => {
  utility.logColdStart(); // First invocation: "This is a cold start!"
  // Subsequent invocations: "This is a warm start"

  return { statusCode: 200, body: 'Success' };
};

Using getColdStart Method

import { Utility } from '@aws-lambda-powertools/commons';

// Create utility instance outside handler
const utility = new Utility();

export const handler = async (event: unknown, context: unknown) => {
  // This will be true on first invocation, false afterwards
  const isColdStart = utility.getColdStart();

  if (isColdStart) {
    // Perform one-time initialization
    console.log('Performing cold start initialization');
    // Load configuration, establish connections, etc.
  }

  // Regular handler logic
  return { statusCode: 200, body: 'Success' };
};

Custom Logger with Cold Start Detection

import { Utility } from '@aws-lambda-powertools/commons';

class CustomLogger extends Utility {
  private serviceName: string;

  constructor(serviceName?: string) {
    super();
    this.serviceName =
      serviceName && this.isValidServiceName(serviceName)
        ? serviceName
        : this.defaultServiceName;
  }

  public log(message: string, metadata?: object): void {
    const logEntry = {
      timestamp: new Date().toISOString(),
      service: this.serviceName,
      message,
      coldStart: this.getColdStart(),
      ...metadata,
    };

    console.log(JSON.stringify(logEntry));
  }
}

const logger = new CustomLogger('my-service');

export const handler = async (event: unknown, context: unknown) => {
  // First invocation logs with coldStart: true
  // Subsequent invocations log with coldStart: false
  logger.log('Processing request', { eventType: event.type });

  return { statusCode: 200, body: 'Success' };
};

Checking Initialization Type

import { Utility } from '@aws-lambda-powertools/commons';

class MyUtility extends Utility {
  constructor() {
    super();

    const initType = this.getInitializationType();

    switch (initType) {
      case 'on-demand':
        console.log('Lambda initialized on-demand');
        break;
      case 'provisioned-concurrency':
        console.log('Lambda using provisioned concurrency');
        break;
      case 'unknown':
        console.log('Unable to determine initialization type');
        break;
    }
  }
}

Service Name Validation

import { Utility } from '@aws-lambda-powertools/commons';

class ConfigurableUtility extends Utility {
  private serviceName: string;

  constructor(serviceName?: string) {
    super();

    // Validate and set service name
    if (this.isValidServiceName(serviceName)) {
      this.serviceName = serviceName!;
    } else {
      this.serviceName = this.defaultServiceName;
      console.warn(
        `Invalid service name provided, using default: ${this.defaultServiceName}`
      );
    }
  }

  public getServiceName(): string {
    return this.serviceName;
  }
}

Using PT_VERSION

import { PT_VERSION } from '@aws-lambda-powertools/commons';

console.log('Powertools version:', PT_VERSION); // e.g., "2.29.0"

// Use in user agent strings, logs, or metrics
const userAgent = `MyApp/1.0 Powertools/${PT_VERSION}`;

Cold Start Behavior

The cold start detection follows these principles:

  1. Initialization Type Detection: Checks AWS_LAMBDA_INITIALIZATION_TYPE environment variable
  2. On-Demand Execution: For on-demand Lambda executions, the first invocation is marked as cold start
  3. Provisioned Concurrency: When using provisioned concurrency, executions are not marked as cold starts
  4. State Persistence: The Utility instance persists across invocations in the same execution environment
  5. Automatic Reset: After the first invocation, the cold start flag is automatically set to false

Lambda Execution Environment Lifecycle

Understanding the Lambda execution environment lifecycle is important:

  • Init Phase (Cold Start):

    • Create/unfreeze execution environment
    • Download function code and layers
    • Initialize extensions
    • Initialize runtime
    • Run initialization code (module scope)
  • Invoke Phase (All Invocations):

    • Execute handler function
    • Process event
    • Return response
  • Shutdown Phase:

    • Runtime shutdown
    • Clean up extensions

The Utility class helps identify when your code is running during the first invocation versus subsequent invocations in the same execution environment.

Use Cases for Cold Start Detection

Common use cases include:

  • Conditional Initialization: Perform expensive one-time setup only during cold starts
  • Metrics and Logging: Add cold start indicators to metrics and logs
  • Performance Monitoring: Track cold start frequency and duration
  • Connection Pooling: Establish database connections during cold starts, reuse in warm starts
  • Cache Warming: Pre-load caches or configurations during initialization
  • Debugging: Add conditional logging for cold start scenarios