As organizations construct fashionable functions with event-driven architectures (EDA), they typically search options that decrease infrastructure administration overhead whereas maximizing developer productiveness. Amazon Managed Streaming for Apache Kafka (Amazon MSK) and AWS Lambda collectively present a serverless, scalable, and cost-efficient platform for real-time event-driven processing.
On this submit, we describe how one can simplify your event-driven utility structure utilizing AWS Lambda with Amazon MSK. We show the way to configure Lambda as a client for Kafka subjects, together with a cross-account setup and the way to optimize worth and efficiency for these functions.
Why use Lambda with Amazon MSK?
Prospects constructing event-driven functions have a number of key priorities in the case of their structure decisions. They usually search to scale back their operational overhead through the use of Amazon Internet Providers (AWS) to deal with the advanced, underlying infrastructure elements so their groups can deal with core enterprise logic. Moreover, builders choose a streamlined expertise that minimizes the necessity for repetitive boilerplate code, enabling them to be extra productive and deal with creating worth. Moreover, these prospects need to obtain each scalability and cost-effectiveness with out the burden of managing compute infrastructure straight. Lambda integration with Amazon MSK successfully addresses these necessities, delivering a complete resolution that mixes the advantages of serverless computing with managed Kafka providers. For instance, an ecommerce firm can use Amazon MSK to gather real-time clickstream information from its web site and course of these occasions utilizing AWS Lambda. With this integration, they’ll set off Lambda features to replace advice fashions, ship personalised affords, or analyze consumer habits immediately—with out provisioning or managing servers. The important thing advantages of utilizing Lambda with Amazon MSK embrace:
- Simplicity by native integration – AWS Lambda affords native integration with Amazon MSK by a connector useful resource known as occasion supply mapping. You need to use this integration to straight affiliate a Kafka matter—whether or not it’s on Amazon MSK or a self-managed Kafka cluster—as an occasion supply for a Lambda operate with out writing customized client logic. With only a few configuration steps, occasion supply mapping handles partition task, offset monitoring, and parallelized batch processing beneath the hood. It makes use of the Kafka client group protocol to distribute matter partitions throughout a number of concurrent Lambda invocations, helps batch windowing, and allows at-least-once supply semantics. Furthermore, it routinely commits offsets upon profitable operate execution whereas dealing with retries and dead-letter queue (DLQ) routing for failed information, considerably decreasing the operational overhead historically related to Kafka customers.
- Auto scaling and throughput controls – When utilizing AWS Lambda with Amazon MSK by occasion supply mapping, Lambda routinely scales by assigning a devoted occasion poller per Kafka partition, enabling parallel, partition-based processing. This permits the system to elastically deal with various visitors with out handbook intervention. For superior management, provisioned concurrency pre-initializes Lambda execution environments, eliminating chilly begins and delivering constant low-latency efficiency. Moreover, with provisioned occasion supply mapping, you possibly can configure the minimal and most variety of Kafka pollers, offering exact management over throughput and concurrency. That is superb for functions with unpredictable visitors patterns or strict latency necessities.
- Price-effectiveness – AWS Lambda makes use of a pay-per-use mannequin by which you solely pay for compute time and variety of invocations. When built-in with Amazon MSK, there aren’t any fees for idle time, making it superb for bursty or low-frequency Kafka workloads. You possibly can additional optimize prices by tuning batch measurement and batch window settings. For mission-critical workloads, provisioned concurrency offers constant efficiency with managed pricing.
- Occasion filtering – AWS Lambda helps occasion filtering for Amazon MSK occasion sources, which implies you possibly can course of solely the Kafka information that match particular standards. This reduces pointless operate invocations and optimizes your operate prices. You possibly can outline as much as 5 filters per occasion supply mapping (with the choice to request a rise to 10). Every filter makes use of a JSON-based sample to specify the situations a document should meet to be processed. Filters may be utilized utilizing the AWS Administration Console, AWS Command Line Interface (AWS CLI), or AWS Serverless Utility Mannequin (AWS SAM) templates. For extra particulars and examples, check with the AWS Lambda documentation on occasion filtering with Amazon MSK.
- Dealing with Availability Zone outage on your client – Amazon MSK allows excessive availability on your Kafka brokers by distributing them throughout a number of Availability Zones inside a Area. To keep up excessive availability throughout your utility, you equally want a client that provides excessive availability. AWS Lambda affords excessive availability and resilience by operating your client features throughout a number of Availability Zones in a Area. Which means even when one Availability Zone experiences an outage, your Lambda operate will proceed to function in different wholesome Availability Zones. Whereas Lambda manages safety patching and Availability Zone failure situations, you possibly can focus in your utility logic.
- Cross-account occasion processing – Cross-account connectivity between AWS Lambda and Amazon MSK permits a Lambda operate in a single AWS account to devour information from an MSK cluster in one other account utilizing MSK multi-VPC personal connectivity powered by AWS PrivateLink. This setup is especially useful for organizations that centralize Kafka infrastructure whereas sustaining separate accounts for various functions or groups.
- Help for JSON, Avro, Protobuf, and Schema Registries – AWS Lambda helps Kafka occasions in JSON, Avro and Protobuf codecs by way of occasion supply mapping. It integrates with AWS Glue Schema registry, Confluent Cloud Schema registry, and self-managed Confluent Schema registry , enabling native schema validation, filtering, and deserialization with out customized code.
How Lambda processes messages out of your Kafka matter
Lambda makes use of occasion supply mappings to course of information from Amazon MSK by actively polling Kafka subjects by occasion pollers that invoke Lambda features with batches of information. These mappings are Lambda managed assets designed for high-throughput, stream-based processing. By default, Lambda detects the OffsetLag for all partitions in your Kafka matter and routinely scales pollers primarily based on visitors. For top-throughput functions, you possibly can allow provisioned mode to outline minimal and most pollers, and your occasion supply mapping auto scales between the minimal and most outlined values. Within the provisioned mode, every poller can course of as much as 5 MBps and helps concurrent Lambda invocations.
After Lambda processes every batch, it commits the offsets of the messages in that batch. In case your operate returns an error for a message in a batch, Lambda retries the entire batch of messages till processing succeeds or the messages expire. You possibly can ship information that fail all retry makes an attempt to an on-failure vacation spot for later processing. To keep up ordered processing inside a partition, Lambda limits the utmost occasion pollers to the variety of partitions within the matter. When establishing Kafka as a Lambda occasion supply, you possibly can specify a client group ID to let Lambda be a part of an current Kafka client group. If different customers are lively in that group, Lambda will obtain solely a part of the subject’s messages. If the group exists, Lambda begins from the group’s dedicated offset, ignoring the StartingPosition. The next diagram illustrates this circulate.
Walkthrough: Construct a serverless Kafka app with AWS Lambda
Observe these steps to construct a serverless utility that consumes messages from an MSK cluster utilizing AWS Lambda:
- Create an Amazon MSK cluster. Use the AWS Administration Console or AWS CLI to create your MSK cluster. When the cluster is up, create your Kafka matter(s). For detailed directions, check with the Amazon MSK documentation.
- Create a Lambda operate utilizing the AWS Administration Console or the AWS CLI. To be taught extra about making a Lambda operate, check with Create your first Lambda operate. The Lambda operate’s execution function must have the next permissions:
- Entry to connect with your MSK cluster
- Permissions to handle elastic community interfaces in your VPC
- To attach Lambda to Amazon MSK as a client, arrange occasion supply mapping to hyperlink your MSK matter with the Lambda operate. This permits Lambda to routinely ballot for brand spanking new messages and course of them. Observe the information on the way to configure occasion supply mapping.
For reference, configuring occasion supply mapping includes three steps:
- Community setup – Within the default occasion supply mapping mode, it’s worthwhile to configure a networking setup utilizing a PrivateLink endpoint or NAT gateway for occasion supply mapping to invoke Lambda features. In provisioned mode, no networking configuration is required (and also you don’t incur the price of networking elements).
- Occasion supply mapping parameter configuration – This includes setting crucial configuration parameters for the occasion supply mapping to have the ability to ballot messages out of your Kafka cluster. This consists of the MSK cluster, matter title, client group ID, authentication methodology, and optionally, schema registry, scaling mode. You possibly can configure the scaling mode for provisioned throughput, together with batch measurement, batch window, and occasion filtering on your occasion supply mapping.
- Entry permissions – This includes configuring required permissions to entry the required AWS assets, and consists of configuring permissions for the operate to execute the code, permissions for the occasion supply mapping to entry your MSK cluster, and permissions for Lambda to entry your VPC assets.
The next screenshot reveals the console setup for configuring Amazon MSK occasion supply mapping, together with the Amazon MSK set off associated fields.
The next screenshot reveals occasion poller configuration.
The next screenshot reveals further settings you need to use, relying in your use case.
Optimizing AWS Lambda for stream processing with Amazon MSK
When constructing real-time information processing pipelines with Amazon MSK and AWS Lambda, it’s essential to tune your setup for each efficiency and cost-efficiency. Lambda affords highly effective serverless compute capabilities, however to get probably the most out of it in a streaming context, it’s worthwhile to make just a few key optimizations:
- Allow provisioned concurrency for low-latency processing – For workloads which can be delicate to latency—chilly begins can introduce undesirable delays. By enabling provisioned concurrency, you possibly can pre-warm a specified variety of Lambda cases in order that they’re at all times able to deal with visitors instantly. This eliminates chilly begins and offers constant response instances, which is essential for latency-critical use circumstances.
- Allow provisioned mode for occasion supply mapping for high-throughput processing – For Kafka workloads with stringent throughput necessities, activate the provisioned mode. The optimum configuration of minimal and most occasion pollers on your Kafka occasion supply mapping is determined by your utility’s efficiency necessities. Begin with the default minimal occasion pollers to baseline the efficiency profile and modify occasion pollers primarily based on noticed message processing patterns and your utility’s efficiency necessities. For workloads with spiky visitors and strict efficiency wants, improve the minimal occasion pollers to deal with sudden surges. You possibly can fine-tune the minimal occasion pollers by evaluating your required throughput, your noticed throughput, which is determined by elements such because the ingested messages per second and common payload measurement, and utilizing the throughput capability of 1 occasion poller (as much as 5 MB/s) as reference. To keep up ordered processing inside a partition, Lambda caps the utmost occasion pollers on the variety of partitions within the matter.
- Optimize message batching utilizing measurement and windowing – By integrating Lambda with Amazon MSK, you possibly can management how messages are batched earlier than they’re despatched to your operate. Tuning parameters comparable to batch measurement (the variety of information per invocation: 1–10,000 information) and most batching window (how lengthy to attend for a full batch: 0–300 seconds) can considerably impression efficiency. Bigger batches imply fewer invocations, which reduces overhead and improves throughput. Nonetheless, it’s essential to strike a stability—too massive a batch or window may introduce undesirable processing delays. Monitor your stream’s habits and modify these settings primarily based on throughput necessities and acceptable latency.
- Apply filters to scale back pointless invocations – Not each document in your Kafka matter may require processing. To keep away from pointless Lambda invocations (and related prices), apply filtering logic straight when configuring the occasion supply mapping. With Lambda, you possibly can outline filtering (as much as 10 filters) standards in order that solely related information set off your operate. This helps scale back compute time, decrease noise, and optimize your funds, particularly when coping with high-throughput subjects with combined content material. For Amazon MSK, Lambda commits offsets for matched and unmatched messages after efficiently invoking the operate.
Conclusion
By combining Amazon MSK with AWS Lambda, you possibly can seamlessly construct fashionable, serverless event-driven functions. This integration eliminates the necessity to handle client teams, compute infrastructure, or scaling logic so groups can deal with delivering enterprise worth quicker.
Whether or not you’re integrating Kafka into microservices, remodeling information pipelines, or constructing reactive functions, Lambda with Amazon MSK is a strong and versatile serverless resolution. For detailed documentation on the way to configure Lambda with Amazon MSK, check with the AWS Lambda Developer Information. For extra serverless studying assets, go to Serverless Land.
In regards to the Authors
Tarun Rai Madan is a Principal Product Supervisor at Amazon Internet Providers (AWS). He focuses on serverless applied sciences and leads product technique to assist prospects obtain accelerated enterprise outcomes with event-driven functions, utilizing providers like AWS Lambda, AWS Step Capabilities, Apache Kafka, and Amazon SQS/SNS. Previous to AWS, he was an engineering chief within the semiconductor business, and led improvement of high-performance processors for wi-fi, automotive, and information middle functions.
Masudur Rahaman Sayem is a Streaming Information Architect at AWS with over 25 years of expertise within the IT business. He collaborates with AWS prospects worldwide to architect and implement subtle information streaming options that handle advanced enterprise challenges. As an skilled in distributed computing, Sayem focuses on designing large-scale distributed methods structure for max efficiency and scalability. He has a eager curiosity and fervour for distributed structure, which he applies to designing enterprise-grade options at web scale.