Stream data processing with Mage

May 30, 2023 · 19 minute read

Shashank Mishra

Data Engineering

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

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.

Source: Giphy

Why is kafka a popular component of streaming applications?

Apache Kafka

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.

Source: 

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.

Source: 

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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:

1
docker exec -i -t -u root $(docker ps | grep docker_kafka | cut -d' ' -f1) /bin/bash
  • Create a topic:

1
2
$KAFKA_HOME/bin/kafka-topics.sh --create --partitions 4 --bootstrap-server kafka:9092 -
topic test
  • List all available topics in Kafka instance:

1
$KAFKA_HOME/bin/kafka-topics.sh --bootstrap-server kafka:9092 --list
  • Start a producer on topic named 

    test

    :

1
$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:

1
2
3
4
5
>hello
>this is a test
>test 1
>test 2
>test 3
  • Open another terminal and start a consumer on the topic named 

    test

    :

1
2
$KAFKA_HOME/bin/kafka-console-consumer.sh --from-beginning --bootstrap-server kafka:9092
--topic=test
  • The output should look something like this:

1
2
3
4
5
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:

1
2
3
4
5
6
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:

1
docker network create -d bridge kafka-docker_default
  • Check that it exists:

1
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:

1
2
3
4
5
6
7
8
9
10
11
12
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:

1
2
3
4
5
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:

1
2
3
4
5
6
7
8
9
10
11
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:

1
2
3
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:

1
2
3
[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

    :

1
pip install kafka-python
  • Open a Python shell and write the following code to publish messages:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[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:

1
2
3
4
5
6
7
8
9
10
11
12
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:

  • Once the trigger is created, click the 

    Start trigger

    button at the top of the page to make the streaming pipeline active.

Source: 

Conclusion

In conclusion, 

Mage

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.

Start building for free

No need for a credit card to get started.
Trying out Mage to build ranking models won’t cost a cent.

No need for a credit card to get started. Trying out Mage to build ranking models won’t cost a cent.

 2024 Mage Technologies, Inc.
 2024 Mage Technologies, Inc.