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.1.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.1-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: stream2pg-0.1.1.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.1.tar.gz
Algorithm Hash digest
SHA256 712762ccabaed721af2ee6d98ee5a99ca4472f26f41715e4a97aea7444ca90f2
MD5 f56328dea2282ba9ddc8ebd92cb357cd
BLAKE2b-256 f351352b63b1c90fe5964fb9d9cbb318af623bdaf124e99738daac2c57b92181

See more details on using hashes here.

File details

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

File metadata

  • Download URL: stream2pg-0.1.1-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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c1565d58cc77bd6ab324b51d52cc6b7b2c934cc983407b76495da788c375b374
MD5 5842278bf9e252fc29374549c9d1cfdc
BLAKE2b-256 7beb07496e7dafd46919f98a9455aa0f472845cf25902fb1e9f5e27c6b647e8a

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