Stream data processing with Mage
Tags: streaming, data, dataengineering, kafka
Published: 2023-06-13 01:55:37

## TLDR
Dive into the implementation of stream data processing with Mage, using Kafka as source.

## Outline
- Introduction to Mage
- Why is kafka a popular component of streaming applications?
- Step by step guide to create streaming pipeline on Mage
- Conclusion

## Introduction to Mage
[Mage](https://www.mage.ai/) is a powerful data processing tool allowing integration and synchronization of data from third-party sources. It supports building real-time and batch pipelines using Python, SQL, and R, making data transformation simple and efficient. Moreover, it enables running, monitoring, and orchestrating thousands of pipelines, ensuring a smooth data operation without the risk of data loss or interruption.

_<center>![Image description](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExMzAxM2Y5ZDlhN2FiMTMyZTY1MzFiNjU2OWM2MDc4NjllNTg0MjFjOSZlcD12MV9pbnRlcm5hbF9naWZzX2dpZklkJmN0PWc/vKHKDIdvxvN7vTAEOM/giphy.gif) 
Source: Giphy_</center>


## Why is kafka a popular component of streaming applications?

[Apache Kafka](https://kafka.apache.org/) is an open-source stream-processing software platform developed by LinkedIn and later donated to the Apache Software Foundation. It's built on the publish-subscribe messaging system and designed to handle real-time data feeds. Kafka is essentially a distributed event log service that is fault-tolerant, highly scalable, and provides high throughput for publishing and subscribing records.

Given its robust features, Kafka is a popular component of streaming applications due to the following reasons:

- _Performance and Scalability:_ Kafka can handle real-time data feeds on a large scale, processing millions of messages per second. Its distributed architecture allows for effortless scalability.
- _Durability and Reliability:_ Kafka's distributed commit log ensures robust data persistence, safeguarding against data loss. If a node fails, the data can still be retrieved from other nodes, hence ensuring reliability.
- _Fault Tolerance:_ Kafka can handle system failures without impacting the availability of data streams, which is crucial for applications that require constant, uninterrupted access to data.
- _Real-time Processing:_ Kafka supports both batch and real-time use cases, providing developers with flexibility when creating various applications.
- _Integration Capabilities:_ Kafka can integrate with a wide range of programming languages and data systems, making it versatile for differing application needs.

Kafka's popularity stems from its high performance, reliability, fault tolerance, real-time processing, and comprehensive integration capabilities.

_<center>![Image description](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExNTQ3YTViOGQ3MWIyZDU3ZWYwODc0NDhkMGUxY2Y2OTBiZmY4ZTg4NyZlcD12MV9pbnRlcm5hbF9naWZzX2dpZklkJmN0PWc/IHuF78peMmj3G/giphy.gif) 
Source: Giphy_</center>

## Step by step guide to create streaming pipeline on Mage

Dive into a comparison of Flink and Spark based on their performance benchmarks and scalability. Discover how they handle processing speed, in-memory computing, resource management, and more.

- _Processing Speed:_ Flink excels in **low-latency**, high-throughput stream processing, while Spark is known for its fast batch processing capabilities. Both frameworks can process large volumes of data quickly, with Flink focusing on real-time analytics and Spark catering to **batch** data processing tasks.
- _In-Memory Computing:_ Both Flink and Spark leverage in-memory computing, which allows them to cache intermediate results during data processing tasks. This approach significantly reduces the time spent on **disk I/O** operations and improves overall performance.
- _Resource Management:_ Flink and Spark can efficiently manage resources by dynamically allocating and deallocating them according to workload requirements. This enables both frameworks to scale horizontally, handling large-scale data processing tasks across multiple nodes in a distributed environment.
- _Adaptive Query Execution:_ Spark's Adaptive Query Execution (**AQE**) feature optimizes query execution plans at runtime, allowing it to adapt to changing data and workload characteristics. This results in improved performance and resource utilization. Flink, on the other hand, does not currently have an equivalent feature.
- _Backpressure Handling:_ Flink is designed to handle backpressure, ensuring that the system remains stable even under high loads. This is achieved through its built-in flow control mechanisms, which prevent data processing bottlenecks. Spark Streaming, in contrast, may **struggle** to handle **backpressure**, leading to potential performance degradation.
- _Data Partitioning:_ Both Flink and Spark utilize data partitioning techniques to improve parallelism and optimize resource utilization during data processing tasks. While Spark employs RDDs and data partitioning strategies like Hash and Range partitioning, Flink uses **operator chaining** and pipelined execution to optimize data processing performance.

_<center>![Image description](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZDhhMTEyYzYzM2Y1YWMwZTM3NGE0ZDdiMDYyYTM2ZTc1ZDljNmM1YSZlcD12MV9pbnRlcm5hbF9naWZzX2dpZklkJmN0PWc/5GoVLqeAOo6PK/giphy.gif) 
Source: Giphy_</center>

## Recommendations for choosing the right tool for specific use cases

Set up Kafka

Here is a quick guide on how to run and use Kafka locally.

- Clone repository: `git clone https://github.com/wurstmeister/kafka-docker.git`
- Change directory into that repository: `cd kafka-docker`
- Edit the `docker-compose.yml` file to match this:

```
version: "2"
services:
  zookeeper:
    image: wurstmeister/zookeeper:3.4.6
    ports:
      - "2181:2181"
  kafka:
    build: .
    container_name: docker_kafka
    ports:
      - "9092:9092"
    expose:
      - "9093"
    environment:
      KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9093,OUTSIDE://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT
      KAFKA_LISTENERS: INSIDE://0.0.0.0:9093,OUTSIDE://0.0.0.0:9092
      KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
```

- Start Docker: `docker-compose up`
- Start a terminal session in the running container:

```
docker exec -i -t -u root $(docker ps | grep docker_kafka | cut -d' ' -f1) /bin/bash
```

- Create a topic:

```
$KAFKA_HOME/bin/kafka-topics.sh --create --partitions 4 --bootstrap-server kafka:9092 -
topic test
```

- List all available topics in Kafka instance:

```
$KAFKA_HOME/bin/kafka-topics.sh --bootstrap-server kafka:9092 --list
```

- Start a producer on topic named `test`:

```
$KAFKA_HOME/bin/kafka-console-producer.sh --broker-list kafka:9092 --topic=test
```

- Send messages to the topic named `test` by typing the following in the terminal:

```
>hello
>this is a test
>test 1
>test 2
>test 3
```

- Open another terminal and start a consumer on the topic named `test`:

```
$KAFKA_HOME/bin/kafka-console-consumer.sh --from-beginning --bootstrap-server kafka:9092
--topic=test
```

- The output should look something like this:

```
hello
test 1
test 3
this is a test
test 2
```

Setup stream data ingestion in Mage
- Run the following command to run Docker in network mode:

```
docker run -it -p 6789:6789 -v $(pwd):/home/src \
  --env AWS_ACCESS_KEY_ID=your_access_key_id \
  --env AWS_SECRET_ACCESS_KEY=your_secret_access_key \
  --env AWS_REGION=your_region \
  --network kafka-docker_default \
  mageai/mageai /app/run_app.sh  mage start default_repo
```

- If the network named `kafka-docker_default` doesn’t exist, create a new network:

```
docker network create -d bridge kafka-docker_default
```

- Check that it exists:

```
docker network ls
```

If not able to connect with Kafka locally in a Docker container using Mage, in a Docker container the follow these steps:

- Clone Mage: `git clone https://github.com/mage-ai/mage-ai.git`
- Change directory into Mage: `cd mage-ai`
- Edit the `docker-compose.yml` file to match this:

```
version: '3'
services:
  server:
    ... (original config)
    networks:
      - kafka
  app:
    ... (original config)
networks:
  kafka:
    name: kafka-docker_default
    	external: true
```

- Run the following script in terminal: `./scripts/dev.sh`

This will run Mage in development mode, which runs it in a Docker container using docker compose instead of docker run.

Create streaming data pipeline
- Open Mage in your browser.
- Click + `New pipeline`, then select `Streaming`.
- Add a data loader block, select `Kafka`, and paste the following:

```
connector_type: kafka
bootstrap_server: "localhost:9092"
topic: test
consumer_group: unique_consumer_group
batch_size: 100
```

- By default, the `bootstrap_server` is set to `localhost:9092`, If you’re running Mage in a container, the `bootstrap_server` should be `kafka:9093`
- Messages are consumed from source in micro batch mode for better efficiency. The default batch size is 100. You can adjust the batch size in the source config.
- Add a transformer block and paste the following:

```
from typing import Dict, List

if 'transformer' not in globals():
    from mage_ai.data_preparation.decorators import transformer

@transformer
def transform(messages: List[Dict], *args, **kwargs):
    for msg in messages:
        print(msg)

    return messages
```

- Add a data exporter block, select OpenSearch and paste the following:

```
connector_type: opensearch
host: https://search-something-abcdefg123456.us-west-1.es.amazonaws.com/
index_name: python-test-index
```

- Change the `host` to match your OpenSearch domain’s endpoint.
- Change the `index_name` to match the index you want to export data into.

Test pipeline

- Open the streaming pipeline you just created, and in the right side panel near the bottom, click the button Execute pipeline to test the pipeline.
- You should see an output like this:

```
[streaming_pipeline_test] Start initializing kafka consumer.
[streaming_pipeline_test] Finish initializing kafka consumer.
[streaming_pipeline_test] Start consuming messages from kafka.
```

Publish messages using Python

- Open a terminal on your local workstation.
- Install `kafka-python`:

```
pip install kafka-python
```

- Open a Python shell and write the following code to publish messages:

```
from kafka import KafkaProducer
from random import random
import json

topic = 'test'
producer = KafkaProducer(
    bootstrap_servers='kafka:9093',
)

def publish_messages(limit):
    for i in range(limit):
        data = {
            'title': 'test_title',
            'director': 'Bennett Miller',
            'year': '2011',
            'rating': random(),
        }
        producer.send(topic, json.dumps(data).encode('utf-8'))

publish_messages(5)
```

- Once you run the code snippet above, go back to your streaming pipeline in Mage and the output should look like this:

```
[streaming_pipeline_test] Start initializing kafka consumer.
[streaming_pipeline_test] Finish initializing kafka consumer.
[streaming_pipeline_test] Start consuming messages from kafka.
[streaming_pipeline_test] [Kafka] Receive message 2:16: v=b'{"title": "test_title",
"director": "Bennett Miller", "year": "2011", "rating": 0.7010424523477785}',
time=1665618592.226788
[streaming_pipeline_test] [Kafka] Receive message 0:16: v=b'{"title": "test_title",
"director": "Bennett Miller", "year": "2011", "rating": 0.7886308380991354}',
time=1665618592.2268753
[streaming_pipeline_test] [Kafka] Receive message 0:17: v=b'{"title": "test_title",
"director": "Bennett Miller", "year": "2011", "rating": 0.0673276352704153}',
time=1665618592.2268832
[streaming_pipeline_test] [Kafka] Receive message 3:10: v=b'{"title": "test_title",
"director": "Bennett Miller", "year": "2011", "rating": 0.37935417366095525}',
time=1665618592.2268872
[streaming_pipeline_test] [Kafka] Receive message 3:11: v=b'{"title": "test_title",
"director": "Bennett Miller", "year": "2011", "rating": 0.21110511524126563}',
time=1665618592.2268918
[streaming_pipeline_test] {'title': 'test_title', 'director': 'Bennett Miller', 'year':
'2011', 'rating': 0.7010424523477785}
[streaming_pipeline_test] {'title': 'test_title', 'director': 'Bennett Miller', 'year':
'2011', 'rating': 0.7886308380991354}
[streaming_pipeline_test] {'title': 'test_title', 'director': 'Bennett Miller', 'year':
'2011', 'rating': 0.0673276352704153}
[streaming_pipeline_test] {'title': 'test_title', 'director': 'Bennett Miller', 'year':
'2011', 'rating': 0.37935417366095525}
[streaming_pipeline_test] {'title': 'test_title', 'director': 'Bennett Miller', 'year':
'2011', 'rating': 0.21110511524126563}
[streaming_pipeline_test] [Opensearch] Batch ingest data [{'title': 'test_title',
'director': 'Bennett Miller', 'year': '2011', 'rating': 0.7010424523477785}, {'title':
'test_title', 'director': 'Bennett Miller', 'year': '2011', 'rating': 0.7886308380991354},
{'title': 'test_title', 'director': 'Bennett Miller', 'year': '2011', 'rating':
0.0673276352704153}, {'title': 'test_title', 'director': 'Bennett Miller', 'year': '2011',
'rating': 0.37935417366095525}, {'title': 'test_title', 'director': 'Bennett Miller',
'year': '2011', 'rating': 0.21110511524126563}], time=1665618592.2294626
```

Consume messages using Python


- If you want to programmatically consume messages from a Kafka topic, here is a code snippet:

```
from kafka import KafkaConsumer
import time

topic = 'test'
consumer = KafkaConsumer(
    topic,
    group_id='test',
    bootstrap_servers='kafka:9093',
)

for message in consumer:
    print(f"{message.partition}:{message.offset}: v={message.value}, time={time.time()}")
```

Run in production

If you want to programmatically consume messages from a Kafka topic, here is a code snippet:

- [Create a trigger](https://docs.mage.ai/design/data-pipeline-management#create-trigger).
- Once the trigger is created, click the Start trigger button at the top of the page to make the streaming pipeline active.

_<center>![Image description](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZDgyYTFjMDlhMTdiYzE2MGUzNTExNjM5MTY5YTViZjcxZjk3ZTI1NCZlcD12MV9pbnRlcm5hbF9naWZzX2dpZklkJmN0PWc/tkYaChn7aZClW/giphy.gif) 
Source: Giphy_</center>

## Conclusion

In conclusion, [Mage](https://www.mage.ai) is an exceptional tool for stream data processing, adept at managing data from various sources and transforming it through real-time and batch pipelines using Python, SQL, and R. It stands out in its capacity to efficiently handle thousands of pipelines simultaneously, ensuring smooth operations and data integrity. Given the increasing need for real-time data processing in today's data-driven world, Mage is positioned as a vital tool in the arsenal of data professionals. Its versatility and robust capabilities make it a reliable choice for handling complex and voluminous streaming data.

_Link to the original blog: https://www.mage.ai/blog/stream-data-processing-with-Mage_