or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

event-sources.mdfunction-invocation.mdfunction-management.mdfunction-urls.mdindex.mdlayers-aliases.mdpagination-waiters.md
tile.json

pagination-waiters.mddocs/

Pagination and Waiters

Utilities for handling paginated responses efficiently and waiting for resource state changes in AWS Lambda operations.

Pagination Utilities

The AWS Lambda Client provides paginator classes for efficiently handling paginated list operations without manually managing pagination tokens.

List Functions Paginator

Automatically handles pagination when listing Lambda functions.

class ListFunctionsPaginator {
  constructor(config: LambdaClient, input: ListFunctionsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListFunctionsCommandOutput>;
}

Additional Paginators

The Lambda client provides paginators for all list operations that support pagination:

// List aliases for a function
class ListAliasesPaginator {
  constructor(config: LambdaClient, input: ListAliasesCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListAliasesCommandOutput>;
}

// List code signing configurations
class ListCodeSigningConfigsPaginator {
  constructor(config: LambdaClient, input: ListCodeSigningConfigsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListCodeSigningConfigsCommandOutput>;
}

// List event source mappings
class ListEventSourceMappingsPaginator {
  constructor(config: LambdaClient, input: ListEventSourceMappingsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListEventSourceMappingsCommandOutput>;
}

// List function event invoke configurations  
class ListFunctionEventInvokeConfigsPaginator {
  constructor(config: LambdaClient, input: ListFunctionEventInvokeConfigsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListFunctionEventInvokeConfigsCommandOutput>;
}

// List function URL configurations
class ListFunctionUrlConfigsPaginator {
  constructor(config: LambdaClient, input: ListFunctionUrlConfigsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListFunctionUrlConfigsCommandOutput>;
}

// List functions by code signing config
class ListFunctionsByCodeSigningConfigPaginator {
  constructor(config: LambdaClient, input: ListFunctionsByCodeSigningConfigCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListFunctionsByCodeSigningConfigCommandOutput>;
}

// List layer versions
class ListLayerVersionsPaginator {
  constructor(config: LambdaClient, input: ListLayerVersionsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListLayerVersionsCommandOutput>;
}

// List layers
class ListLayersPaginator {
  constructor(config: LambdaClient, input: ListLayersCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListLayersCommandOutput>;
}

// List provisioned concurrency configurations
class ListProvisionedConcurrencyConfigsPaginator {
  constructor(config: LambdaClient, input: ListProvisionedConcurrencyConfigsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListProvisionedConcurrencyConfigsCommandOutput>;
}

// List versions by function
class ListVersionsByFunctionPaginator {
  constructor(config: LambdaClient, input: ListVersionsByFunctionCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListVersionsByFunctionCommandOutput>;
}

Usage Example:

import { LambdaClient, paginateListFunctions } from "@aws-sdk/client-lambda";

const client = new LambdaClient({ region: "us-east-1" });

// Method 1: Using the paginate helper function
const paginator = paginateListFunctions(
  { client, pageSize: 25 },
  { MaxItems: 25 }
);

for await (const page of paginator) {
  console.log(`Found ${page.Functions?.length || 0} functions in this page`);
  for (const func of page.Functions || []) {
    console.log(`Function: ${func.FunctionName} (${func.Runtime})`);
  }
}

// Method 2: Using the paginator class directly
import { ListFunctionsPaginator } from "@aws-sdk/client-lambda";

const functionsPaginator = new ListFunctionsPaginator(client, {});

for await (const page of functionsPaginator) {
  console.log(`Processing page with ${page.Functions?.length || 0} functions`);
  // Process functions in this page
}

List Event Source Mappings Paginator

Handles pagination for event source mapping listings.

class ListEventSourceMappingsPaginator {
  constructor(config: LambdaClient, input: ListEventSourceMappingsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListEventSourceMappingsCommandOutput>;
}

Usage Example:

import { paginateListEventSourceMappings } from "@aws-sdk/client-lambda";

const paginator = paginateListEventSourceMappings(
  { client, pageSize: 10 },
  { FunctionName: "my-function" }
);

for await (const page of paginator) {
  for (const mapping of page.EventSourceMappings || []) {
    console.log(`Event Source: ${mapping.EventSourceArn}`);
    console.log(`State: ${mapping.State}`);
  }
}

List Aliases Paginator

Efficiently paginate through function aliases.

class ListAliasesPaginator {
  constructor(config: LambdaClient, input: ListAliasesCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListAliasesCommandOutput>;
}

List Layers Paginator

Paginate through available Lambda layers.

class ListLayersPaginator {
  constructor(config: LambdaClient, input: ListLayersCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListLayersCommandOutput>;
}

List Layer Versions Paginator

Paginate through versions of a specific layer.

class ListLayerVersionsPaginator {
  constructor(config: LambdaClient, input: ListLayerVersionsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListLayerVersionsCommandOutput>;
}

Other Available Paginators

class ListCodeSigningConfigsPaginator {
  constructor(config: LambdaClient, input: ListCodeSigningConfigsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListCodeSigningConfigsCommandOutput>;
}

class ListFunctionEventInvokeConfigsPaginator {
  constructor(config: LambdaClient, input: ListFunctionEventInvokeConfigsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListFunctionEventInvokeConfigsCommandOutput>;
}

class ListFunctionUrlConfigsPaginator {
  constructor(config: LambdaClient, input: ListFunctionUrlConfigsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListFunctionUrlConfigsCommandOutput>;
}

class ListFunctionsByCodeSigningConfigPaginator {
  constructor(config: LambdaClient, input: ListFunctionsByCodeSigningConfigCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListFunctionsByCodeSigningConfigCommandOutput>;
}

class ListProvisionedConcurrencyConfigsPaginator {
  constructor(config: LambdaClient, input: ListProvisionedConcurrencyConfigsCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListProvisionedConcurrencyConfigsCommandOutput>;
}

class ListVersionsByFunctionPaginator {
  constructor(config: LambdaClient, input: ListVersionsByFunctionCommandInput);
  [Symbol.asyncIterator](): AsyncIterator<ListVersionsByFunctionCommandOutput>;
}

Waiter Utilities

Waiters provide a convenient way to poll for resource state changes, automatically handling the retry logic and backoff strategies.

Function Active Waiter

Waits for a Lambda function to reach the Active state after creation or update.

function waitForFunctionActive(
  config: WaiterConfiguration<LambdaClient>,
  input: GetFunctionCommandInput
): Promise<WaiterResult>;

function waitForFunctionActiveV2(
  config: WaiterConfiguration<LambdaClient>,
  input: GetFunctionConfigurationCommandInput
): Promise<WaiterResult>;

Usage Example:

import { LambdaClient, waitForFunctionActive, CreateFunctionCommand } from "@aws-sdk/client-lambda";

const client = new LambdaClient({ region: "us-east-1" });

// Create a function
const createCommand = new CreateFunctionCommand({
  FunctionName: "my-new-function",
  Runtime: "nodejs18.x",
  Role: "arn:aws:iam::123456789012:role/lambda-role",
  Handler: "index.handler",
  Code: {
    ZipFile: Buffer.from("exports.handler = async () => 'Hello World';")
  }
});

const createResult = await client.send(createCommand);

// Wait for the function to become active
try {
  const waiterResult = await waitForFunctionActive(
    {
      client,
      maxWaitTime: 300, // Maximum wait time in seconds
      minDelay: 1,      // Minimum delay between checks in seconds
      maxDelay: 10      // Maximum delay between checks in seconds
    },
    { FunctionName: "my-new-function" }
  );
  
  if (waiterResult.state === "SUCCESS") {
    console.log("Function is now active and ready to use");
  }
} catch (error) {
  console.error("Function failed to become active:", error);
}

Function Exists Waiter

Waits for a Lambda function to exist (useful after creation operations).

function waitForFunctionExists(
  config: WaiterConfiguration<LambdaClient>,
  input: GetFunctionCommandInput
): Promise<WaiterResult>;

// Wait for function to be updated
function waitForFunctionUpdated(
  config: WaiterConfiguration<LambdaClient>,
  input: GetFunctionConfigurationCommandInput
): Promise<WaiterResult>;

function waitForFunctionUpdatedV2(
  config: WaiterConfiguration<LambdaClient>,
  input: GetFunctionConfigurationCommandInput
): Promise<WaiterResult>;

// Wait for published version to be active
function waitForPublishedVersionActive(
  config: WaiterConfiguration<LambdaClient>,
  input: GetFunctionConfigurationCommandInput
): Promise<WaiterResult>;

Usage Example:

import { waitForFunctionExists } from "@aws-sdk/client-lambda";

try {
  const waiterResult = await waitForFunctionExists(
    {
      client,
      maxWaitTime: 120, // 2 minutes
      minDelay: 2,
      maxDelay: 15
    },
    { FunctionName: "my-function" }
  );
  
  if (waiterResult.state === "SUCCESS") {
    console.log("Function exists and can be accessed");
  }
} catch (error) {
  console.error("Function does not exist or timeout reached:", error);
}

Function Updated Waiters

Wait for function updates to complete successfully.

function waitForFunctionUpdated(
  config: WaiterConfiguration<LambdaClient>,
  input: GetFunctionCommandInput
): Promise<WaiterResult>;

function waitForFunctionUpdatedV2(
  config: WaiterConfiguration<LambdaClient>,
  input: GetFunctionConfigurationCommandInput
): Promise<WaiterResult>;

Usage Example:

import { LambdaClient, waitForFunctionUpdated, UpdateFunctionCodeCommand } from "@aws-sdk/client-lambda";

const client = new LambdaClient({ region: "us-east-1" });

// Update function code
const updateCommand = new UpdateFunctionCodeCommand({
  FunctionName: "my-function",
  ZipFile: updatedCode
});

await client.send(updateCommand);

// Wait for the update to complete
try {
  const waiterResult = await waitForFunctionUpdated(
    {
      client,
      maxWaitTime: 300,
      minDelay: 5,
      maxDelay: 30
    },
    { FunctionName: "my-function" }
  );
  
  if (waiterResult.state === "SUCCESS") {
    console.log("Function update completed successfully");
  }
} catch (error) {
  console.error("Function update failed or timed out:", error);
}

Published Version Active Waiter

Waits for a published function version to become active.

function waitForPublishedVersionActive(
  config: WaiterConfiguration<LambdaClient>,
  input: GetFunctionCommandInput
): Promise<WaiterResult>;

Usage Example:

import { waitForPublishedVersionActive, PublishVersionCommand } from "@aws-sdk/client-lambda";

// Publish a new version
const publishCommand = new PublishVersionCommand({
  FunctionName: "my-function",
  Description: "Version with new features"
});

const publishResult = await client.send(publishCommand);
const versionNumber = publishResult.Version;

// Wait for the published version to become active
try {
  const waiterResult = await waitForPublishedVersionActive(
    {
      client,
      maxWaitTime: 180,
      minDelay: 3,
      maxDelay: 20
    },
    { 
      FunctionName: "my-function",
      Qualifier: versionNumber
    }
  );
  
  if (waiterResult.state === "SUCCESS") {
    console.log(`Version ${versionNumber} is now active`);
  }
} catch (error) {
  console.error(`Version ${versionNumber} failed to become active:`, error);
}

Core Types

interface WaiterConfiguration<Client> {
  /** The service client to use for polling */
  client: Client;
  /** Maximum time to wait in seconds */
  maxWaitTime?: number;
  /** Minimum delay between polling attempts in seconds */
  minDelay?: number;
  /** Maximum delay between polling attempts in seconds */
  maxDelay?: number;
  /** Custom backoff strategy */
  backoffRate?: number;
}

interface WaiterResult {
  /** The final state of the waiter */
  state: WaiterState;
  /** The reason for the final state */
  reason?: any;
}

enum WaiterState {
  SUCCESS = "SUCCESS",
  FAILURE = "FAILURE",
  RETRY = "RETRY",
  TIMEOUT = "TIMEOUT"
}

interface PaginatorConfig {
  /** The service client */
  client: LambdaClient;
  /** Maximum items per page */
  pageSize?: number;
  /** Starting pagination token */
  startingToken?: string;
}

Advanced Usage Patterns

Processing All Functions with Error Handling

import { LambdaClient, paginateListFunctions } from "@aws-sdk/client-lambda";

const client = new LambdaClient({ region: "us-east-1" });

async function processAllFunctions() {
  try {
    const paginator = paginateListFunctions(
      { client, pageSize: 50 },
      { MaxItems: 50 }
    );

    let totalFunctions = 0;
    const functionsByRuntime = new Map<string, number>();

    for await (const page of paginator) {
      for (const func of page.Functions || []) {
        totalFunctions++;
        
        // Track functions by runtime
        const runtime = func.Runtime || 'unknown';
        functionsByRuntime.set(runtime, (functionsByRuntime.get(runtime) || 0) + 1);
        
        // Process individual function
        console.log(`Processing: ${func.FunctionName}`);
        
        // Add your function processing logic here
        // await processFunction(func);
      }
    }

    console.log(`Total functions processed: ${totalFunctions}`);
    console.log('Functions by runtime:', Object.fromEntries(functionsByRuntime));
    
  } catch (error) {
    console.error('Error processing functions:', error);
    throw error;
  }
}

await processAllFunctions();

Combining Waiters with Resource Creation

import { 
  LambdaClient, 
  CreateFunctionCommand, 
  PublishVersionCommand,
  CreateAliasCommand,
  waitForFunctionActive,
  waitForPublishedVersionActive 
} from "@aws-sdk/client-lambda";

async function deployFunctionWithAlias(functionConfig: any) {
  const client = new LambdaClient({ region: "us-east-1" });
  
  try {
    // Step 1: Create function
    console.log("Creating function...");
    const createCommand = new CreateFunctionCommand(functionConfig);
    await client.send(createCommand);
    
    // Step 2: Wait for function to be active
    console.log("Waiting for function to become active...");
    await waitForFunctionActive(
      { client, maxWaitTime: 300 },
      { FunctionName: functionConfig.FunctionName }
    );
    
    // Step 3: Publish version
    console.log("Publishing version...");
    const publishCommand = new PublishVersionCommand({
      FunctionName: functionConfig.FunctionName,
      Description: "Initial version"
    });
    const versionResult = await client.send(publishCommand);
    
    // Step 4: Wait for version to be active
    console.log("Waiting for published version to be active...");
    await waitForPublishedVersionActive(
      { client, maxWaitTime: 180 },
      { 
        FunctionName: functionConfig.FunctionName,
        Qualifier: versionResult.Version
      }
    );
    
    // Step 5: Create alias
    console.log("Creating alias...");
    const aliasCommand = new CreateAliasCommand({
      FunctionName: functionConfig.FunctionName,
      Name: "PROD",
      FunctionVersion: versionResult.Version,
      Description: "Production alias"
    });
    await client.send(aliasCommand);
    
    console.log("Deployment completed successfully!");
    return {
      functionName: functionConfig.FunctionName,
      version: versionResult.Version,
      alias: "PROD"
    };
    
  } catch (error) {
    console.error("Deployment failed:", error);
    throw error;
  }
}

Batch Processing with Pagination

async function batchUpdateFunctions(updates: Record<string, any>) {
  const client = new LambdaClient({ region: "us-east-1" });
  const results = [];
  
  // Get all functions using pagination
  const paginator = paginateListFunctions({ client }, {});
  
  for await (const page of paginator) {
    const updatePromises = (page.Functions || [])
      .filter(func => updates[func.FunctionName || ''])
      .map(async (func) => {
        try {
          const updateConfig = updates[func.FunctionName || ''];
          
          // Apply update
          const updateCommand = new UpdateFunctionConfigurationCommand({
            FunctionName: func.FunctionName,
            ...updateConfig
          });
          
          await client.send(updateCommand);
          
          // Wait for update to complete
          await waitForFunctionUpdated(
            { client, maxWaitTime: 180 },
            { FunctionName: func.FunctionName }
          );
          
          return { functionName: func.FunctionName, status: 'success' };
        } catch (error) {
          console.error(`Failed to update ${func.FunctionName}:`, error);
          return { functionName: func.FunctionName, status: 'failed', error };
        }
      });
    
    // Process updates in parallel for this page
    const pageResults = await Promise.all(updatePromises);
    results.push(...pageResults);
  }
  
  return results;
}