# EventSourceMapping

Defines a Lambda EventSourceMapping resource.

Usually, you won't need to define the mapping yourself. This will usually be done by
event sources. For example, to add an SQS event source to a function:

```ts
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as eventsources from 'aws-cdk-lib/aws-lambda-event-sources';

declare const handler: lambda.Function;
declare const queue: sqs.Queue;

handler.addEventSource(new eventsources.SqsEventSource(queue));
```

The `SqsEventSource` class will automatically create the mapping, and will also
modify the Lambda's execution role so it can consume messages from the queue.

Extends: Construct › Resource › EventSourceMapping
Implements: IResource, IEventSourceMapping, IEnvironmentAware, IEventSourceMappingRef, IConstruct, IDependable

- CloudFormation: [`AWS::Lambda::EventSourceMapping`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-lambda-eventsourcemapping.html)
- L1 type: [`CfnEventSourceMapping`](/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.CfnEventSourceMapping.html)
- Source: [`aws-lambda/lib/event-source-mapping.ts`](https://github.com/aws/aws-cdk/blob/v2.274.0/packages/aws-cdk-lib/aws-lambda/lib/event-source-mapping.ts#L471)
- Type last changed: v2.224.0 · 13 Nov 2025

## Example

```ts
// The code below shows an example of how to instantiate this type.
// The values are placeholders you should change.
import * as cdk from 'aws-cdk-lib';
import { aws_kms as kms } from 'aws-cdk-lib';
import { aws_lambda as lambda } from 'aws-cdk-lib';

declare const eventSourceDlq: lambda.IEventSourceDlq;
declare const filters: any;
declare const function_: lambda.Function;
declare const key: kms.Key;
declare const schemaRegistry: lambda.ISchemaRegistry;
declare const sourceAccessConfigurationType: lambda.SourceAccessConfigurationType;
const eventSourceMapping = new lambda.EventSourceMapping(this, 'MyEventSourceMapping', {
  target: function_,

  // the properties below are optional
  batchSize: 123,
  bisectBatchOnError: false,
  enabled: false,
  eventSourceArn: 'eventSourceArn',
  filterEncryption: key,
  filters: [{
    filtersKey: filters,
  }],
  kafkaBootstrapServers: ['kafkaBootstrapServers'],
  kafkaConsumerGroupId: 'kafkaConsumerGroupId',
  kafkaTopic: 'kafkaTopic',
  logLevel: lambda.EventSourceMappingLogLevel.INFO,
  maxBatchingWindow: cdk.Duration.minutes(30),
  maxConcurrency: 123,
  maxRecordAge: cdk.Duration.minutes(30),
  metricsConfig: {
    metrics: [lambda.MetricType.EVENT_COUNT],
  },
  onFailure: eventSourceDlq,
  parallelizationFactor: 123,
  provisionedPollerConfig: {
    maximumPollers: 123,
    minimumPollers: 123,
    pollerGroupName: 'pollerGroupName',
  },
  reportBatchItemFailures: false,
  retryAttempts: 123,
  schemaRegistryConfig: schemaRegistry,
  sourceAccessConfigurations: [{
    type: sourceAccessConfigurationType,
    uri: 'uri',
  }],
  startingPosition: lambda.StartingPosition.TRIM_HORIZON,
  startingPositionTimestamp: 123,
  supportS3OnFailureDestination: false,
  tumblingWindow: cdk.Duration.minutes(30),
});
```

## Initializer

```ts
new EventSourceMapping(scope: Construct, id: string, props: EventSourceMappingProps)
```

## Construct Props

- `batchSize`: number = Amazon Kinesis, Amazon DynamoDB, and Amazon MSK is 100 records. The default for Amazon SQS is 10 messages. For standard SQS queues, the maximum is 10,000. For FIFO SQS queues, the maximum is 10. — The largest number of records that AWS Lambda will retrieve from your event source at the time of invoking your function.

  Your function receives an
  event with all the retrieved records.

  Valid Range: Minimum value of 1. Maximum value of 10000.

  **Default:** Amazon Kinesis, Amazon DynamoDB, and Amazon MSK is 100 records. The default for Amazon SQS is 10 messages. For standard SQS queues, the maximum is 10,000. For FIFO SQS queues, the maximum is 10.

- `bisectBatchOnError`: boolean = false — If the function returns an error, split the batch in two and retry.

- `enabled`: boolean = true — Set to false to disable the event source upon creation.

- `eventSourceArn`: string = not set if using a self managed Kafka cluster, throws an error otherwise — The Amazon Resource Name (ARN) of the event source.

  Any record added to
  this stream can invoke the Lambda function.

  **Default:** not set if using a self managed Kafka cluster, throws an error otherwise

- `filterEncryption`: [IKey](/cdk/api/v2/docs/aws-cdk-lib.aws_kms.IKey.html) = none — Add Customer managed KMS key to encrypt Filter Criteria.

- `filters`: { [key: string]: any }[] = none — Add filter criteria to Event Source.

- `kafkaBootstrapServers`: string[] = none — A list of host and port pairs that are the addresses of the Kafka brokers in a self managed "bootstrap" Kafka cluster that a Kafka client connects to initially to bootstrap itself.

  They are in the format `abc.example.com:9096`.

- `kafkaConsumerGroupId`: string = none — The identifier for the Kafka consumer group to join.

  The consumer group ID must be unique among all your Kafka event sources. After creating a Kafka event source mapping with the consumer group ID specified, you cannot update this value. The value must have a length between 1 and 200 and full the pattern '[a-zA-Z0-9-\/*:_+=.@-]*'. For more information, see [Customizable consumer group ID](https://docs.aws.amazon.com/lambda/latest/dg/with-msk.html#services-msk-consumer-group-id).

- `kafkaTopic`: string = no topic — The name of the Kafka topic.

- `logLevel`: [EventSourceMappingLogLevel](/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.EventSourceMappingLogLevel.html) = No logging — Configuration for logging verbosity from the event source mapping poller.

  This configuration controls the verbosity of the logs generated by the polling infrastructure
  that reads events from the event source. The logs provide insights into the internal operations
  of the event source mapping, including connection status, polling behavior, and error conditions.

- `maxBatchingWindow`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) = Duration.seconds(0) — The maximum amount of time to gather records before invoking the function.

  Maximum of Duration.minutes(5)

- `maxConcurrency`: number = No specific limit. — The maximum concurrency setting limits the number of concurrent instances of the function that an Amazon SQS event source can invoke.

- `maxRecordAge`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) = infinite or until the record expires. — The maximum age of a record that Lambda sends to a function for processing.

  Valid Range:
  * Minimum value of 60 seconds
  * Maximum value of 7 days

  **Default:** infinite or until the record expires.

- `metricsConfig`: [MetricsConfig](/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.MetricsConfig.html) = Enhanced monitoring is disabled — Configuration for enhanced monitoring metrics collection When specified, enables collection of additional metrics for the stream event source.

- `onFailure`: [IEventSourceDlq](/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.IEventSourceDlq.html) = discarded records are ignored — An Amazon S3, Amazon SQS queue or Amazon SNS topic destination for discarded records.

- `parallelizationFactor`: number = 1 — The number of batches to process from each shard concurrently.

  Valid Range:
  * Minimum value of 1
  * Maximum value of 10

- `provisionedPollerConfig`: [ProvisionedPollerConfig](/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.ProvisionedPollerConfig.html) = no provisioned pollers — Configuration for provisioned pollers that read from the event source.

  When specified, allows control over the minimum and maximum number of pollers
  that can be provisioned to process events from the source.

- `reportBatchItemFailures`: boolean = false — Allow functions to return partially successful responses for a batch of records.

- `retryAttempts`: number = infinite or until the record expires. — The maximum number of times to retry when the function returns an error.

  Set to `undefined` if you want lambda to keep retrying infinitely or until
  the record expires.

  Valid Range:
  * Minimum value of 0
  * Maximum value of 10000

  **Default:** infinite or until the record expires.

- `schemaRegistryConfig`: [ISchemaRegistry](/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.ISchemaRegistry.html) = none — Specific configuration settings for a Kafka schema registry.

- `sourceAccessConfigurations`: [SourceAccessConfiguration](/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.SourceAccessConfiguration.html)[] = none — Specific settings like the authentication protocol or the VPC components to secure access to your event source.

- `startingPosition`: [StartingPosition](/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.StartingPosition.html) = no starting position — The position in the DynamoDB, Kinesis or MSK stream where AWS Lambda should start reading.

- `startingPositionTimestamp`: number = no timestamp — The time from which to start reading, in Unix time seconds.

- `supportS3OnFailureDestination`: boolean = false — Check if support S3 onfailure destination(OFD).

  Kinesis, DynamoDB, MSK and self managed kafka event support S3 OFD

- `target`: [IFunction](/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.IFunction.html) (required) — The target AWS Lambda function.

- `tumblingWindow`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) = None — The size of the tumbling windows to group records sent to DynamoDB or Kinesis.

## Properties

- `env`: [ResourceEnvironment](/cdk/api/v2/docs/aws-cdk-lib.interfaces.ResourceEnvironment.html) (required) — The environment this resource belongs to.

  For resources that are created and managed in a Stack (those created by
  creating new class instances like `new Role()`, `new Bucket()`, etc.), this
  is always the same as the environment of the stack they belong to.

  For referenced resources (those obtained from referencing methods like
  `Role.fromRoleArn()`, `Bucket.fromBucketName()`, etc.), they might be
  different than the stack they were imported into.

- `eventSourceMappingArn`: string (required) — The ARN of the event source mapping (i.e. arn:aws:lambda:region:account-id:event-source-mapping/event-source-mapping-id).

- `eventSourceMappingId`: string (required) — The identifier for this EventSourceMapping.

- `eventSourceMappingRef`: [EventSourceMappingReference](/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_lambda.EventSourceMappingReference.html) (required) — A reference to a EventSourceMapping resource.

- `node`: [Node](/cdk/api/v2/docs/constructs.Node.html) (required) — The tree node.

- `PROPERTY_INJECTION_ID`: string (required) (static) — Uniquely identifies this class.

- `stack`: [Stack](/cdk/api/v2/docs/aws-cdk-lib.Stack.html) (required) — The stack in which this resource is defined.

## Methods

- `applyCrossStackReferenceStrength(strength: ReferenceStrength): void` — Override the cross-stack reference strength for this resource.

  When set, any cross-stack reference to this resource will use the specified
  mechanism instead of the global default determined by the
  `@aws-cdk/core:defaultCrossStackReferences` context key. This is useful for
  selectively weakening specific references to avoid the "deadly embrace" problem
  without changing the app-wide default.

  **Parameters**

  - `strength` — - The reference strength to use for this resource.

- `applyRemovalPolicy(policy: RemovalPolicy): void` — Apply the given removal policy to this resource.

  The Removal Policy controls what happens to this resource when it stops
  being managed by CloudFormation, either because you've removed it from the
  CDK application or because you've made a change that requires the resource
  to be replaced.

  The resource can be deleted (`RemovalPolicy.DESTROY`), or left in your AWS
  account for data recovery and cleanup later (`RemovalPolicy.RETAIN`).

- `fromEventSourceMappingId(scope: Construct, id: string, eventSourceMappingId: string): IEventSourceMapping` (static) — Import an event source into this stack from its event source id.

- `isConstruct(x: any): boolean` (static) — Checks if `x` is a construct.

  Use this method instead of `instanceof` to properly detect `Construct`
  instances, even when the construct library is symlinked.

  Explanation: in JavaScript, multiple copies of the `constructs` library on
  disk are seen as independent, completely different libraries. As a
  consequence, the class `Construct` in each copy of the `constructs` library
  is seen as a different class, and an instance of one class will not test as
  `instanceof` the other class. `npm install` will not create installations
  like this, but users may manually symlink construct libraries together or
  use a monorepo tool: in those cases, multiple copies of the `constructs`
  library can be accidentally installed, and `instanceof` will behave
  unpredictably. It is safest to avoid using `instanceof`, and using
  this type-testing method instead.

  **Parameters**

  - `x` — Any object.

  **Returns:** true if `x` is an object created from a class which extends `Construct`.

- `isOwnedResource(construct: IConstruct): boolean` (static) — Returns true if the construct was created by CDK, and false otherwise.

- `isResource(construct: IConstruct): boolean` (static) — Check whether the given construct is a Resource.

- `toString(): string` — Returns a string representation of this construct.

- `with(...mixins: IMixin[]): IConstruct` — Applies one or more mixins to this construct.

  Mixins are applied in order. The list of constructs is captured at the
  start of the call, so constructs added by a mixin will not be visited.
  Use multiple `with()` calls if subsequent mixins should apply to added
  constructs.
