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.
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;
}/**
* The current version of the Powertools for AWS Lambda package.
* This is an auto-generated constant representing the package version.
*/
const PT_VERSION: string;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' };
};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' };
};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' };
};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;
}
}
}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;
}
}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}`;The cold start detection follows these principles:
AWS_LAMBDA_INITIALIZATION_TYPE environment variableUnderstanding the Lambda execution environment lifecycle is important:
Init Phase (Cold Start):
Invoke Phase (All Invocations):
Shutdown Phase:
The Utility class helps identify when your code is running during the first invocation versus subsequent invocations in the same execution environment.
Common use cases include: