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",
        "subscribe_pattern": "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",
    "subscribe_pattern": "mobility-.*",
    "starting_offsets": "earliest",
    "fail_on_data_loss": "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.0.tar.gz (9.3 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.0-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: stream2pg-0.1.0.tar.gz
  • Upload date:
  • Size: 9.3 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.0.tar.gz
Algorithm Hash digest
SHA256 9f03ff8e679244d29146f112f07c444694c88f114d6f175c015142c90478ff6e
MD5 a6e10579814fbb6b7b5f7d746bee5945
BLAKE2b-256 93bcc192f2bda8fd7ec78cdeade16ef356c1dc1f83cb5f1b53b70f1552972a77

See more details on using hashes here.

File details

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

File metadata

  • Download URL: stream2pg-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 7.8 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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 db4d9a670859a50d105580d90ae1f8685b7bfe442cf35cc1fcc5e86ee658fe81
MD5 a1e9879dfab76317f5683b83bf490015
BLAKE2b-256 94ad8629cc18ae6c11defb774e20b7db0badd6cdacf6aef21cdf8117c60c470b

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