I Tried Out Queue Mode for Self-Managed Kafka Event Source Mapping in AWS Lambda

I Tried Out Queue Mode for Self-Managed Kafka Event Source Mapping in AWS Lambda

I tried Queue mode event source mapping (ESM) with Kafka 4.2 on EC2 and a single-partition topic. With up to 10 concurrent invocations, 60 records taking 5 seconds each were processed in 31.6 seconds. Setup steps are included.
2026.11.29

This page has been translated by machine translation. View original

Introduction

On November 2, 2026, AWS Lambda added support for Queue mode in self-managed Kafka event source mappings (ESM).

https://aws.amazon.com/about-aws/whats-new/2026/11/aws-lambda-queue-kafka-esm/

In Queue mode, multiple event pollers fetch records from the same partition at the same time and process them in parallel.

This article shares the results of trying Queue mode with a topic that has a single partition.

Test environment

  • Region: Tokyo (ap-northeast-1)
  • Kafka
    • Runtime environment: t3.medium EC2 (Amazon Linux 2023, public subnet in the default VPC)
    • Software: apache/kafka:4.2.0 (Docker, single node, KRaft)
    • share.version: 1
    • Authentication: none (PLAINTEXT)
    • Topic: kq-test (1 partition, replication factor 1)
    • Commands on EC2: run with Systems Manager Run Command (AWS-RunShellScript). The EC2 instance has an instance profile with an IAM role that has AmazonSSMManagedInstanceCore attached
  • Network
    • ESM placement: two private subnets whose default route (0.0.0.0/0) points to a NAT Gateway
    • Connection to the broker: private IP within the VPC
    • Security group: shared by the Kafka EC2 instance and the ESM. Inbound allows only all traffic from the security group itself
  • Lambda
    • Function: Python 3.13, 128 MB, timeout 300 seconds
    • ESM: batch-size 1, on-demand mode

Environment setup

Kafka

Queue mode works with Apache Kafka 4.2 or later with share groups enabled.

https://docs.aws.amazon.com/lambda/latest/dg/polling-kafka-queue.html

For the test, I started apache/kafka:4.2.0 as a single node on EC2. I saved the startup script as kafka-userdata.sh and passed it to the EC2 user-data. Because it is a single node, I set the following values to 1.

  • Replication factor of the offsets topic
  • Replication factor and min ISR of the transaction log
  • Replication factor and min ISR of the share coordinator's state topic
kafka-userdata.sh
#!/bin/bash
# User-data for EC2 (Amazon Linux 2023). Starts a single-node Kafka 4.2.0 with Docker.
set -eux
dnf install -y docker
systemctl enable --now docker

TOKEN=$(curl -sS -X PUT http://169.254.169.254/latest/api/token -H 'X-aws-ec2-metadata-token-ttl-seconds: 300')
IP=$(curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/local-ipv4)

docker run -d --name kafka --network host --restart unless-stopped \
  -e KAFKA_NODE_ID=1 \
  -e KAFKA_PROCESS_ROLES=broker,controller \
  -e KAFKA_LISTENERS=PLAINTEXT://0.0.0.0:9092,CONTROLLER://127.0.0.1:9093 \
  -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://${IP}:9092 \
  -e KAFKA_CONTROLLER_LISTENER_NAMES=CONTROLLER \
  -e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT \
  -e KAFKA_INTER_BROKER_LISTENER_NAME=PLAINTEXT \
  -e KAFKA_CONTROLLER_QUORUM_VOTERS=1@127.0.0.1:9093 \
  -e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 \
  -e KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=1 \
  -e KAFKA_TRANSACTION_STATE_LOG_MIN_ISR=1 \
  -e KAFKA_SHARE_COORDINATOR_STATE_TOPIC_REPLICATION_FACTOR=1 \
  -e KAFKA_SHARE_COORDINATOR_STATE_TOPIC_MIN_ISR=1 \
  -e KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0 \
  apache/kafka:4.2.0

echo "$IP" > /tmp/kafka-ip

You can check whether share groups are enabled with describe in kafka-features.sh. If the FinalizedVersionLevel of share.version is 1, it is enabled.

docker exec kafka /opt/kafka/bin/kafka-features.sh --bootstrap-server <broker>:9092 describe
Feature: share.version	SupportedMinVersion: 0	SupportedMaxVersion: 1	FinalizedVersionLevel: 1	Epoch: 148

Function and execution role

I wrote the function in Python. It waits for the number of seconds specified in the record's sleep field and logs the start and end times as JSON. The file name is lambda_function.py and the handler is lambda_function.handler.

lambda_function.py
import base64
import json
import time

def handler(event, context):
    # Extract the received records (usually 1 because batch-size is 1)
    items = []
    for _tp, records in event["records"].items():
        for r in records:
            value = json.loads(base64.b64decode(r["value"]))
            items.append((r["partition"], r["offset"], value))

    t_start = time.time()
    print(json.dumps({
        "ev": "start", "rid": context.aws_request_id, "t": t_start,
        "items": [{"p": p, "o": o, "id": v.get("id")} for p, o, v in items],
    }))

    for p, o, v in items:
        if v.get("fail"):
            print(json.dumps({"ev": "fail", "rid": context.aws_request_id, "t": time.time(), "id": v.get("id")}))
            raise RuntimeError(f"intentional failure id={v.get('id')}")
        time.sleep(v.get("sleep", 5))

    t_end = time.time()
    print(json.dumps({
        "ev": "end", "rid": context.aws_request_id, "t": t_end,
        "items": [{"p": p, "o": o, "id": v.get("id")} for p, o, v in items],
    }))
    return {"ok": True}

Save the following policy as lambda-esm-ec2-policy.json and attach it to the execution role.

lambda-esm-ec2-policy.json
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["ec2:DescribeSecurityGroups","ec2:DescribeVpcs","ec2:DescribeSubnets","ec2:DescribeNetworkInterfaces","ec2:CreateNetworkInterface","ec2:DeleteNetworkInterface"],"Resource":"*"}]}
aws iam put-role-policy --role-name <実行ロール名> --policy-name esm-ec2 --policy-document file://lambda-esm-ec2-policy.json

ESM in Queue mode

Create an ESM in Queue mode by specifying Queue for ConsumptionMode.

aws lambda create-event-source-mapping --function-name kq-fn \
  --self-managed-event-source '{"Endpoints":{"KAFKA_BOOTSTRAP_SERVERS":["<broker>:9092"]}}' \
  --topics kq-test --batch-size 1 \
  --self-managed-kafka-event-source-config '{"ConsumptionMode":"Queue"}' \
  --source-access-configurations '[{"Type":"VPC_SUBNET","URI":"<subnet-a>"},{"Type":"VPC_SUBNET","URI":"<subnet-c>"},{"Type":"VPC_SECURITY_GROUP","URI":"<sg>"}]'

After the State became Enabled, running get-event-source-mapping returned the following values.

aws lambda get-event-source-mapping --uuid <uuid> --query '{State:State,ConsumptionMode:SelfManagedKafkaEventSourceConfig.ConsumptionMode,BatchSize:BatchSize,MaximumRetryAttempts:MaximumRetryAttempts,ProvisionedPollerConfig:ProvisionedPollerConfig,StartingPosition:StartingPosition,Topics:Topics,LastProcessingResult:LastProcessingResult}'
{
    "State": "Enabled",
    "ConsumptionMode": "Queue",
    "BatchSize": 1,
    "MaximumRetryAttempts": 0,
    "ProvisionedPollerConfig": null,
    "StartingPosition": null,
    "Topics": [
        "kq-test"
    ],
    "LastProcessingResult": "OK"
}

Measurement results

Measurement method

Records are JSON in the form {"id":N,"sleep":S}. After the ESM State became Enabled, I produced them with kafka-console-producer.sh on EC2 using the following produce.sh.

produce.sh

Pass the number of records and the sleep seconds, as in bash produce.sh 60 5.

#!/bin/bash
# usage: produce.sh <count> <sleep-sec> [extra-json-line ...]  (run on EC2)
# Produce count records of {"id":N,"sleep":S} to the topic kq-test. extra lines are added at the beginning.
COUNT=$1; SLEEP=$2; shift 2
IP=$(cat /tmp/kafka-ip)
{
  for l in "$@"; do echo "$l"; done
  for i in $(seq 1 "$COUNT"); do echo "{\"id\":$i,\"sleep\":$SLEEP}"; done
} | docker exec -i kafka /opt/kafka/bin/kafka-console-producer.sh --bootstrap-server "$IP:9092" --topic kq-test

I calculated the concurrency from the start and end logs output by the function. I retrieved the logs with the following command and counted how many intervals from start to end of each invocation overlapped. For --start-time, I specified a time before producing the records.

aws logs filter-log-events --log-group-name /aws/lambda/kq-fn --start-time <投入前のエポックミリ秒> --filter-pattern '{ $.ev = * }' --output json | jq '{events: [.events[] | {timestamp, message}]}'

Concurrency

I produced 60 records with a sleep of 5 seconds to a topic with one partition.

  • Number of invocations: 60
  • Maximum concurrency: 10
  • From the first start to the last end: 31.6 seconds

Taking the first start as 0 seconds, invocations started 10 at a time at 0.0 seconds, 5.6 seconds, 10.9 seconds, 16.0 seconds, 21.3 seconds, and 26.5 seconds.

Summary

Previously, you needed to prepare a consumer for each Kafka partition. With Queue mode now supported, you no longer need to keep up with increases in the number of partitions, and you can use it more simply.

It is limited to workloads where preserving record order is not required, but please try Queue mode as a way to improve throughput.

Share this article

AWSのお困り事はクラスメソッドへ