> ## Documentation Index
> Fetch the complete documentation index at: https://docs.maia.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# MSK pipeline trigger adapter

The MSK pipeline trigger adapter is a packaged, supported AWS Lambda function that triggers a Maia pipeline for each record on an Amazon Managed Streaming for Apache Kafka (MSK) topic. Use it to run pipelines in response to events in Kafka without writing and maintaining your own consumer.

It's a sibling of the Amazon Simple Queue Service (SQS) adapter, described in [SQS pipeline trigger adapter](https://docs.maia.ai/docs/guides/sqs-pipeline-trigger-adapter.md), and uses the same container image. You deploy it with a Terraform module that creates the Lambda function and the AWS resources around it. The adapter runs independently of your Maia runner and doesn't depend on any Maia runner version. One record starts one pipeline run.

The following diagram shows how a record gets from a producer to a pipeline run. Each topic has its own event source mapping, and all the mappings share one poller group. The group uses Lambda's [provisioned mode](https://docs.aws.amazon.com/lambda/latest/dg/kafka-scaling-modes.html), in which event pollers, the compute that reads records from a topic, keep running.

```mermaid theme={null}
flowchart LR
    P[Applications<br/>publishing events]

    subgraph MSK["Amazon MSK (SASL/SCRAM-512)"]
        T1[Topic A]
        T2[Topic B]
    end

    subgraph Pollers["Lambda event source mappings"]
        E1[Mapping for topic A<br/>own consumer group]
        E2[Mapping for topic B<br/>own consumer group]
    end

    Handler[Adapter Lambda function]

    subgraph External["External services"]
        SM[Secrets Manager<br/>API credentials]
        DDB[DynamoDB<br/>Project mappings]
        Maia[Maia API]
    end

    FT[Failure topic<br/>on the same cluster]

    P --> T2
    P --> T1
    T2 --> E2
    T1 --> E1
    E2 --> Handler
    E1 --> Handler
    Handler --> SM
    Handler --> DDB
    Handler --> Maia
    Pollers -. retries spent .-> FT
```

***

## Prerequisites

To use the adapter, you need:

* An Amazon MSK cluster that uses Simple Authentication and Security Layer (SASL) with Salted Challenge Response Authentication Mechanism (SCRAM)-512. The cluster, the topics, and a failure topic must already exist.
* A SCRAM secret in AWS Secrets Manager whose name starts with `AmazonMSK_`, encrypted with a customer managed AWS Key Management Service (KMS) key. MSK doesn't accept the AWS managed key.
* Maia API credentials (a client ID and client secret). If you're not familiar with API credentials in Maia, read [Authenticate to the Maia API](https://docs.maia.ai/docs/api-reference/maia-api-authentication.md).
* An AWS account with permission to create Lambda functions and event source mappings, DynamoDB tables, Amazon Elastic Container Registry (ECR) repositories, Identity and Access Management (IAM) roles and inline policies, CloudWatch log groups and alarms, and Amazon Simple Notification Service (SNS) topics.
* Terraform 1.9 or later and AWS provider 6.28.0 or later. The module needs this provider version because it's the first to support a Kafka failure destination and a poller group.
* A published pipeline to trigger. The adapter can only run published pipelines.

If the cluster enforces Kafka access control lists (ACLs), the SCRAM user needs the following permissions:

* `DescribeConfigs` on the cluster.
* `Describe` and `Read` on each topic and on each consumer group. The consumer group ID is `<function-name>-<topic>`, and `name_prefix` sets the function name.
* Write access on the failure topic, because Lambda's event source mapping, not the adapter, writes failed records there, as the SCRAM user. A Kafka producer needs at least `Write` and `Describe`.

The event source mapping's pollers run in the cluster's virtual private cloud (VPC) and only talk to the brokers, so you don't need a Network Address Translation (NAT) gateway or VPC endpoints. The Lambda function itself runs outside the VPC and reaches DynamoDB, Secrets Manager, and the Maia API over public endpoints.

### Adapter version

Use adapter version 1.2.0 or later. To route a topic that carries its own payload, as described in [Route a topic that carries its own payload](#route-a-topic-that-carries-its-own-payload), use version 1.3.0 or later.

> [!WARNING]
>
> Version 1.2.0 ignores the topic routes setting, so a routed topic's records fail validation and every record goes to the failure topic. An image older than 1.2.0 reads an MSK event as an empty SQS batch and reports success, so MSK commits the offsets and those records never trigger a pipeline. Terraform can't check the image version, so make sure you use a supported version.

***

## Copy the adapter image to your own ECR repository

Lambda only runs images from a private ECR repository in the same region as the function. Copy the adapter image to your own repository as described in [Copy the adapter image to your own ECR repository](https://docs.maia.ai/docs/guides/sqs-pipeline-trigger-adapter.md#copy-the-adapter-image-to-your-own-ecr-repository), and note the image URI.

Copy version 1.2.0 or later (1.3.0 or later for topic routes).

***

## Store your API credentials

The adapter authenticates to Maia using OAuth client credentials. Create a secret in AWS Secrets Manager that contains your client ID and client secret, as described in [Store your API credentials](https://docs.maia.ai/docs/guides/sqs-pipeline-trigger-adapter.md#store-your-api-credentials).

The adapter only runs published pipelines. If the credentials have an account role other than **Super Admin**, they need access to the project (Viewer or higher) and at least the Operator role on the environment. Operator is the lowest environment role that can run published pipelines—Viewer can't. Read [project roles](https://docs.maia.ai/docs/administration/project-roles.md) and [environment roles](https://docs.maia.ai/docs/administration/environment-roles.md).

The secret must exist before you deploy. Terraform doesn't create it. Pass its name to the module as `secret_name`.

***

## Deploy the adapter with Terraform

The adapter has its own Terraform module, `modules/aws/lambda/msk-maia-foundation-adapter`, in the [deployment library](https://github.com/matillion-public/deployment-library). Deploy it as its own Terraform configuration. Neither `runner/aws/ecs` nor `runner/aws/eks` calls it. The deployment library has no tags or releases, so pin `ref` to the commit you want to use, for example `cd3deb7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`:

```hcl theme={null}
module "msk_maia_foundation_adapter" {
  source      = "git::https://github.com/matillion-public/deployment-library.git//modules/aws/lambda/msk-maia-foundation-adapter?ref=<commit-sha>"
  aws_region  = "eu-west-1"
  image_uri   = "<account-id>.dkr.ecr.eu-west-1.amazonaws.com/<repository>:<tag>"
  secret_name = "<secret-name>"

  cluster_arn       = "arn:aws:kafka:eu-west-1:<account-id>:cluster/<cluster-name>/<cluster-id>"
  topics            = ["orders", "refunds"]
  scram_secret_arn  = "arn:aws:secretsmanager:eu-west-1:<account-id>:secret:AmazonMSK_<name>"
  scram_kms_key_arn = "arn:aws:kms:eu-west-1:<account-id>:key/<key-id>"
  failure_topic     = "maia-trigger-failures"
}
```

Then run `terraform init`, `terraform plan`, and `terraform apply`.

The module creates:

* The Lambda function and its execution role.
* One event source mapping for each topic, all in one poller group.
* An optional DynamoDB project mapping table.
* A CloudWatch log group.
* An optional SNS topic and CloudWatch alarms.

### Variables

| Variable | Required | Default | Description |
| - | - | - | - |
| `aws_region` | Required | None | The AWS region the adapter runs in. |
| `image_uri` | Required | None | The URI of the arm64 adapter image in your private ECR repository, in the same region as the function. Use a `<version>-arm64` tag, version 1.2.0 or later (1.3.0 or later for `topic_routes`). |
| `secret_name` | Required | None | The name of the existing AWS Secrets Manager secret that contains your client ID and client secret. |
| `cluster_arn` | Required | None | The Amazon Resource Name (ARN) of the MSK cluster. |
| `topics` | Required | None | The topics whose records trigger pipelines. Each topic gets its own event source mapping. |
| `topic_routes` | Optional | `{}` | Topics whose producers send their own payload, each mapped to the pipeline its records trigger. Requires adapter version 1.3.0 or later. |
| `scram_secret_arn` | Required | None | The ARN of the Secrets Manager secret that holds the SCRAM username and password. |
| `scram_kms_key_arn` | Required | None | The ARN of the customer managed KMS key that encrypts the SCRAM secret. |
| `failure_topic` | Required | None | The topic on the same cluster that receives a record, with its content, once its retries are spent. It must already exist. |
| `starting_position` | Optional | `LATEST` | Where a new consumer group starts reading. `LATEST` avoids triggering a pipeline for every record the topic still retains. |
| `batch_size` | Optional | `1` | The maximum number of records per invocation. At `1`, a record that fails only holds back itself. |
| `minimum_pollers` | Optional | `1` | The number of event pollers each topic's mapping keeps running. |
| `maximum_pollers` | Optional | `10` | The number of event pollers each topic's mapping can scale up to. Concurrency is still capped at one invocation per partition. |
| `maximum_retry_attempts` | Optional | `3` | The number of retries for a failed record before it goes to the failure topic. |
| `create_mapping_table` | Optional | `true` | Creates the DynamoDB table that maps project names to project IDs. Set to `false` to use an existing table. |
| `mapping_table_name` | Optional | `matillion-msk-project-mappings` | The name of the table to create. Used when `create_mapping_table` is `true`. |
| `existing_mapping_table_name` | Optional | None | The name of the existing table. Used when `create_mapping_table` is `false`. |
| `existing_mapping_table_arn` | Optional | None | The ARN of the existing table. Used when `create_mapping_table` is `false`. |
| `matillion_api_url` | Optional | `https://eu1.api.matillion.com/dpc/v1` | The base URL of the Maia pipeline execution API. |
| `matillion_token_url` | Optional | `https://id.core.matillion.com/oauth/dpc/token` | The Maia OAuth token endpoint. |
| `name_prefix` | Optional | `matillion-maia-msk-adapter` | The prefix that sets the names of the function, its consumer groups, and the poller group. |
| `reserved_concurrency` | Optional | `-1` | The reserved concurrent executions for the function. `-1` leaves it unreserved. |
| `create_alarms` | Optional | `true` | Creates the SNS topic and the CloudWatch alarms. |

The module has more optional variables, including the function's memory, timeout, log level, and log retention. For the full list, read the module's `variables.tf` file.

> [!WARNING]
>
> The default API URL is for the EU1 region. If your account is in a different region, replace `eu1` in `matillion_api_url` with the value for your region.

***

## Add project mappings

The adapter uses a DynamoDB table to look up the project ID for the project name and environment in each record. Add one item to the table for each project and environment combination you want to trigger pipelines in, as described in [Add project mappings](https://docs.maia.ai/docs/guides/sqs-pipeline-trigger-adapter.md#add-project-mappings). The table has the same schema as the SQS adapter's table, so both adapters can share one table.

To share the SQS adapter's table, set `create_mapping_table` to `false`, and pass the name and ARN of the table as `existing_mapping_table_name` and `existing_mapping_table_arn`. Use the actual name and ARN from your SQS deployment, which might not be the default. The SQS deployment owns the table, so destroying that deployment also removes the MSK mappings.

***

## Send a record to trigger a pipeline

Produce a record to one of the topics. The record value must be a UTF-8 JSON message in the same format as the SQS adapter uses. The adapter ignores the record key and headers. Each message contains the following fields:

* `project`: The name of the project that contains the pipeline.
* `environment`: The name of the environment to run the pipeline in.
* `job`: The folder path and name of the pipeline, without a file extension, for example `folder/PipelineName`. Don't add `.orch.yaml`.
* `variables`: The scalar variables to pass to the pipeline. Each value can be up to 10,000 characters.
* `gridVariables`: The grid variables to pass to the pipeline.

The whole message can be up to 64 KB. For example:

```json theme={null}
{
  "project": "CustomerDataPipeline",
  "environment": "prod",
  "job": "orders/LoadOrder",
  "variables": { "orderId": "42" }
}
```

The message is a trigger, not data. The pipeline it starts reads and loads its own data. For the full rules for each field, read [Send a message to trigger a pipeline](https://docs.maia.ai/docs/guides/sqs-pipeline-trigger-adapter.md#send-a-message-to-trigger-a-pipeline).

***

## Route a topic that carries its own payload

If a producer sends its own payload instead of the adapter's message format, route the topic to a pipeline with `topic_routes`. This setting requires adapter version 1.3.0 or later. Each route names the project, environment, and pipeline that the topic's records trigger, and the scalar variable that receives the record:

```hcl theme={null}
topic_routes = {
  orders = {
    project          = "CustomerDataPipeline"
    environment      = "prod"
    pipeline         = "mskLoad/LoadOrderEvent"
    payload_variable = "orderEvent"
  }
}
```

The following diagram shows the route for a topic named `orders`. The adapter doesn't parse the record. It passes the value to the pipeline that the route names, and the pipeline does the rest.

```mermaid theme={null}
flowchart LR
    P[Producer] -->|Own payload| T[MSK topic<br/>orders]
    T --> ESM[Event source mapping<br/>one per topic]
    ESM --> FN[Adapter Lambda function]
    FN -->|topic_routes: orders| R[Route<br/>project, environment,<br/>pipeline, payload_variable]
    R --> API[Maia API]
    API --> PL[Pipeline<br/>mskLoad/LoadOrderEvent]
    ESM -. retries spent .-> FT[Failure topic]
```

The adapter base64-encodes the record value into the `payload_variable` and passes these scalar variables to the pipeline:

| Variable | Value |
| - | - |
| `orderEvent` | The record value, base64-encoded. This is the name you set in `payload_variable`. |
| `kafkaTopic` | The topic name. |
| `kafkaPartition` | The record's partition. |
| `kafkaOffset` | The record's offset. |

In the pipeline, decode the payload with `BASE64_DECODE_STRING` and parse it yourself. Base64 encoding keeps a backslash or quotation mark in the payload from breaking the pipeline's SQL.

Keep these points in mind:

* Base64 encoding increases the value size by a third. With the 10,000-character limit for scalar variables, the payload can be about 7,500 bytes.
* The event source mapping can deliver a record more than once. If the pipeline inserts rows, you need to deduplicate them by topic, partition, and offset.
* A topic that isn't in `topic_routes` must carry the adapter's message format.
* A route's topic must be in `topics`, and `payload_variable` can't be `kafkaTopic`, `kafkaPartition`, or `kafkaOffset`. `terraform plan` rejects both.
* Terraform doesn't check the project, environment, or pipeline in a route. If a route names a pipeline that doesn't exist, every record goes to the failure topic. A route the function can't use, such as a pipeline path that contains `..`, stops the function starting, so every record fails until you fix the route.

***

## Handle failed records

Lambda's event source mapping retries a record that fails, including one that the Maia API rejects, `maximum_retry_attempts` times. It then writes the record, with its content, to the failure topic.

The record on the failure topic is a JSON message. Its `payload` field holds the original records with each value base64-encoded, and `requestContext.condition` is `RetryAttemptsExhausted`. To replay a record, decode the value, fix the message, and produce it to the topic again.

The first failure in a partition holds back the rest of that partition until the record succeeds or goes to the failure topic, because a retry redelivers everything from the lowest failed offset. With `batch_size` set to `1`, a bad record only holds back itself.

The following diagram shows what happens to a record that fails at offset 42.

```mermaid theme={null}
sequenceDiagram
    participant K as MSK partition
    participant M as Event source mapping
    participant H as Adapter Lambda function
    participant A as Maia API
    participant F as Failure topic

    K->>M: Record at offset 42
    M->>H: Invoke with the record
    H->>A: Start pipeline run
    A-->>H: Error response
    H-->>M: Report partition and offset 42 as failed
    loop Up to maximum_retry_attempts
        M->>H: Redeliver from offset 42
    end
    M->>F: Write the record with its content
    M->>K: Commit and move on to offset 43
```

When `create_alarms` is `true`, each topic gets a CloudWatch alarm that fires when a record reaches the failure topic or can't be written there. The Lambda errors alarm doesn't see these failures, because the function reports them in its response and doesn't raise an error.

For a topic in `topic_routes`, the alarm only covers failures to start a run. If a run starts and then fails inside the pipeline, the adapter doesn't retry it, the record doesn't reach the failure topic, and no alarm fires. Watch those runs in [Pipeline run history](https://docs.maia.ai/docs/guides/pipeline-run-history.md).

***

## Scaling and cost

* Pollers: Each topic's mapping has its own minimum and maximum pollers, so your baseline is the number of topics multiplied by `minimum_pollers`. The mappings share one poller group, which packs those pollers into shared event poller units of 10 pollers each. A poller group can hold up to 100 topics, and the maximum pollers across the group can't add up to more than 2,000.
* Concurrency: The adapter runs at most one invocation per partition, so the partition counts of your topics set the ceiling for a burst. If you set `reserved_concurrency`, it's one cap shared by every topic, and it must be at least the total partition count.
* Cost: AWS bills provisioned mode in event poller units for as long as the mappings exist. All the module's mappings share one poller group, so they share units instead of each topic being billed separately.
* Renaming the function: Changing `name_prefix` changes the function name, which recreates the mappings with new consumer groups. They start from `starting_position`, not from the old groups' offsets.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.