Skip to main content

Kafka to PostgreSQL sink using Spark Structured Streaming

Project description

stream2pg

Automatically stream JSON data from Kafka into PostgreSQL using Spark Structured Streaming.

Create tables. Evolve schemas. Load data.

PyPI Python

Features

  • 🚀 Kafka → PostgreSQL streaming
  • 🔄 Automatic schema evolution
  • 📦 Spark Structured Streaming
  • 🐘 PostgreSQL integration
  • 📊 Metrics callbacks
  • ⚡ Minimal configuration

How It Works

Given Kafka messages like:

{
  "vehicle_id": 42,
  "speed": 18.7,
  "timestamp": "2025-01-01T12:00:00Z"
}

stream2pg will:

  1. Subscribe to matching Kafka topics
  2. Create PostgreSQL tables automatically
  3. Infer column types
  4. Add new columns when unseen fields appear
  5. Insert records into PostgreSQL

No manual DDL required.

Installation

Development

pip install -e .

From PyPI

pip install stream2pg

Quick Start

from stream2pg import Stream2Pg

config = {
    "postgres": {
        "host": "localhost",
        "port": 5432,
        "dbname": "mobility",
        "user": "postgres",
        "password": "secret",
    },
    "kafka": {
        "bootstrap_servers": "localhost:9092",
        "topic_prefix": "mobility-",
        "starting_offsets": "earliest",
        "fail_on_data_loss": "false",
    },
    "processing": {
        "error_strategy": "SKIP_ON_ERROR",
        "checkpoint_location": "./checkpoints/kafka_to_postgres",
    },
}

sink = Stream2Pg(config)
sink.run()

Metrics

A metrics callback can be provided to observe batch execution.

def on_metrics(
    batch_id,
    row_count,
    inserted_count,
    skipped_count,
    elapsed_ms,
):
    print(
        f"Batch {batch_id}: "
        f"{inserted_count} inserted, "
        f"{skipped_count} skipped "
        f"in {elapsed_ms} ms"
    )

sink = Stream2Pg(config, on_metrics=on_metrics)
sink.run()

Functional API

If you prefer not to instantiate the class directly:

from stream2pg import run

run(config)

Configuration

PostgreSQL

{
    "host": "localhost",
    "port": 5432,
    "dbname": "mobility",
    "user": "postgres",
    "password": "secret",
}

Kafka

{
    "bootstrap_servers": "localhost:9092",
    "topic_prefix": "mobility-",
    "subscribe_pattern": "mobility-.*",
    "starting_offsets": "earliest",
    "fail_on_data_loss": "false",
}
Parameter Description
bootstrap_servers Kafka broker addresses (default: localhost:9092)
topic_prefix Prefix to strip from topic names for table names
subscribe_pattern Kafka topic subscription pattern (default: {prefix}.*)
starting_offsets Where to start reading (default: earliest)
fail_on_data_loss Fail on data loss (default: false)

Processing

{
    "error_strategy": "SKIP_ON_ERROR",
    "checkpoint_location": "./checkpoints/kafka_to_postgres",
}

Error Handling

RAISE

Fail the current batch immediately when an error occurs.

"error_strategy": "RAISE"

SKIP_ON_ERROR

Skip invalid records and continue processing the remaining batch.

"error_strategy": "SKIP_ON_ERROR"

API Reference

Stream2Pg

Stream2Pg(config, on_metrics=None)

Creates a streaming sink instance.

Parameters:

| Parameter | Description | | | - | | config | Configuration dictionary | | on_metrics | Optional metrics callback |

Stream2Pg.run()

Starts the Kafka → PostgreSQL streaming pipeline.

sink.run()

run()

Convenience wrapper around Stream2Pg.

from stream2pg import run

run(config)

Exceptions

ConfigurationError

Raised when the provided configuration is invalid.

from stream2pg.errors import ConfigurationError

Requirements

  • Python 3.9+
  • Apache Spark
  • Kafka
  • PostgreSQL

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

stream2pg-0.1.2.tar.gz (9.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

stream2pg-0.1.2-py3-none-any.whl (8.0 kB view details)

Uploaded Python 3

File details

Details for the file stream2pg-0.1.2.tar.gz.

File metadata

  • Download URL: stream2pg-0.1.2.tar.gz
  • Upload date:
  • Size: 9.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.5

File hashes

Hashes for stream2pg-0.1.2.tar.gz
Algorithm Hash digest
SHA256 09a44beffd3c51eadfc9c9355a3075db59a5f78bd90eb5e050d73e205c8e1fa3
MD5 9b1b1a43aee079f32a19cfab9125ea0f
BLAKE2b-256 38f4d28acbaff6b539f1cfa4d18421e3e5c5b3dd1f966e60913848dff0f1c500

See more details on using hashes here.

File details

Details for the file stream2pg-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: stream2pg-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 8.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.5

File hashes

Hashes for stream2pg-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 fad2d2526609e56612f6229e147b8ccb28bb380453b7aa0a1717250caea8df10
MD5 0e96381687e8eae6a047024e82b114d6
BLAKE2b-256 fb4776785b895d9952cb20600250015c807966d063aa3e6d43a737bb289394a3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page