Skip to main content

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

Metadata

Release files for stream2pg 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for stream2pg 0.1.2
File Size Uploaded Provenance Actions
stream2pg-0.1.2.tar.gz 9.8 kB Without provenance Details for stream2pg-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for stream2pg 0.1.2
File Interpreter ABI Platform Actions
stream2pg-0.1.2-py3-none-any.whl Python 3 none any Details for stream2pg-0.1.2-py3-none-any.whl

Total release size: 17.9 kB

Release files / stream2pg-0.1.2.tar.gz

Download URL stream2pg-0.1.2.tar.gz
Size 9.8 kB
Tags Source
SHA-256 checksum
How to use checksums
09a44beffd3c51eadfc9c9355a3075db59a5f78bd90eb5e050d73e205c8e1fa3
BLAKE2b-256 checksum
How to use checksums
38f4d28acbaff6b539f1cfa4d18421e3e5c5b3dd1f966e60913848dff0f1c500
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.5

Release files / stream2pg-0.1.2-py3-none-any.whl

Download URL stream2pg-0.1.2-py3-none-any.whl
Size 8.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fad2d2526609e56612f6229e147b8ccb28bb380453b7aa0a1717250caea8df10
BLAKE2b-256 checksum
How to use checksums
fb4776785b895d9952cb20600250015c807966d063aa3e6d43a737bb289394a3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.5

Security for stream2pg 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page