Jerome Rajan

0 %
Jerome Rajan
Data & AI Architect at Google
  • Residence:
    India
  • City:
    Mumbai
GCP Agent Platform
GenAI
SQL
Dataproc, EMR
Hadoop
BigQuery
PySpark, Python
Data Pipeline Design
Tableau, Redshift, Snowflake
IBM DataStage
  • AWS Lambda, S3, EMR, SQS, DynamoDB, Step Functions, Cloud Functions
  • Unix Shell Scripting, Python
  • Oracle, DB2, Redis
  • Alteryx, VBA, Blueprism, UiPath
English
Tamil
Hindi
Malayalam
Marathi
Spanish

Real-Time Data Streaming into Kinesis & Ingestion into Postgres Using AWS Glue — Part 1 (Setup)

October 5, 2020

Earlier this year, Amazon announced serverless streaming ETL support in AWS Glue. Under the hood, AWS Glue runs managed Apache Spark enhanced with Glue DynamicFrame abstractions—combining relational-style schema flexibility with distributed Spark execution across the AWS ecosystem.

Before adopting AWS Glue Streaming in production, always weigh cold-start latency, DPU cost, and checkpointing behavior against your SLA requirements. To put the new streaming engine through its paces, I built an end-to-end reference pipeline and documented the setup below.

Architecture Overview

At its foundation, AWS Glue sits atop Apache Spark Core alongside Spark SQL, MLlib, GraphX, and Spark Structured Streaming:

Apache Spark ecosystem stack showing Spark Core, Spark SQL, Spark Streaming, MLlib, and GraphX
The Apache Spark ecosystem powering AWS Glue

Previously, AWS Glue supported only batch ETL jobs. With serverless streaming enabled, Glue jobs can continuously consume micro-batches from Amazon Kinesis Data Streams or Apache Kafka (MSK). In this lab architecture, a simulated IoT producer writes JSON events on EC2, the Kinesis Agent ships them into a Kinesis Data Stream, and AWS Glue Streaming ingests them in real time into both Amazon RDS for PostgreSQL and an Amazon S3 archive bucket:

End-to-end architecture: EC2 IoT simulator to Amazon Kinesis Data Streams, AWS Glue Streaming, RDS PostgreSQL, and S3
Reference streaming architecture

Note: Using PostgreSQL as a sink here is strictly for demonstration—high-throughput IoT analytical workloads in production belong in purpose-built analytical stores or lakehouses.

Prerequisites

  1. Provision an Amazon EC2 instance (t2.micro or t3.micro) with an IAM role granting kinesis:PutRecord and kinesis:PutRecords permissions.
  2. Install the Amazon Kinesis Agent on Amazon Linux: sudo yum install -y aws-kinesis-agent
  3. Create a dedicated log directory under /tmp/aths-kinesis-stream for the simulator to write JSON log files (avoid home directories whose default 700 permissions block the aws-kinesis-agent-user daemon).

Step 1: Set Up the IoT Stream Simulator

The Python script below slices a sample JSON dataset into timestamped log files inside /tmp/aths-kinesis-stream/. You can grab the complete script and sample data from github.com/datasherlock/real-time-demo-data-generator.

Usage: python3 StreamGenerator.py SourceFileName.txt NumOfLines SubjectArea

#!/usr/bin/env python3
import sys
import time

source_data = sys.argv[1]
subject_area = sys.argv[3]
placeholder = f"{subject_area}_LastLine.txt"

def get_line_count():
    i = 0
    with open(source_data, "r") as f:
        for i, _ in enumerate(f, 1):
            pass
    return i

def make_log(start_line, num_lines):
    dest_data = time.strftime(f"/tmp/aths-kinesis-stream/{subject_area}_%Y%m%d-%H%M%S.log")
    with open(source_data, "r") as jsonfile, open(dest_data, "w+") as dstfile:
        input_row = 0
        lines_written = 0
        for line in jsonfile:
            input_row += 1
            if input_row > start_line:
                dstfile.write(line)
                lines_written += 1
                if lines_written >= num_lines:
                    break
    return lines_written

num_lines = int(sys.argv[2]) if len(sys.argv) > 2 else 100
start_line = 0

try:
    with open(placeholder, "r") as f:
        for line in f:
            start_line = int(line.strip())
except IOError:
    start_line = 0

print(f"Writing {num_lines} lines starting at line {start_line}")

total_lines_written = 0
lines_in_file = get_line_count()

while total_lines_written < num_lines:
    written = make_log(start_line, num_lines - total_lines_written)
    total_lines_written += written
    start_line += written
    if start_line >= lines_in_file:
        start_line = 0

print(f"Wrote {total_lines_written} lines.")

with open(placeholder, "w") as f:
    f.write(str(start_line))

Step 2: Create the Amazon Kinesis Data Stream

  1. Open the Amazon Kinesis Console → Data streams → Create data stream.
  2. Provide a stream name (for example, iot-demo-stream) and select Provisioned mode with 1 shard (sufficient for 1 MB/sec or 1,000 records/sec ingress), or run via AWS CLI:
aws kinesis create-stream \
  --stream-name iot-demo-stream \
  --shard-count 1 \
  --region us-east-1

Step 3: Configure the Amazon Kinesis Agent

Rather than writing custom Kinesis Producer Library (KPL) code, we configure /etc/aws-kinesis/agent.json to tail /tmp/aths-kinesis-stream/*.log and publish records automatically. Be sure to set the regional kinesis.endpoint if your stream lives outside us-east-1:

{
  "cloudwatch.emitMetrics": true,
  "kinesis.endpoint": "https://kinesis.us-east-1.amazonaws.com",
  "firehose.endpoint": "",
  "flows": [
    {
      "filePattern": "/tmp/aths-kinesis-stream/*.log",
      "kinesisStream": "KinesisDataStreamName",
      "partitionKeyOption": "RANDOM"
    }
  ]
}

Start and enable the agent service:

sudo service aws-kinesis-agent start
sudo chkconfig aws-kinesis-agent on

Step 4: Run the Simulator & Verify Ingestion

Trigger StreamGenerator.py and tail the Kinesis Agent log to confirm records are being parsed and delivered to your Kinesis Data Stream:

tail -f /var/log/aws-kinesis-agent/aws-kinesis-agent.log

Once records appear in the Kinesis Monitoring tab, head over to Part 2 — Configure AWS Glue Data Catalog Tables & JDBC Crawlers!

Posted in TechnologyTags:
Write a comment
Be Original
Would the boy you were be proud of the man you are?