Skip to main content

A Python library for processing Redis Stream events with consumer groups

Project description

Process Redis Events - Python

A Python library for processing Redis Stream events with consumer groups, providing robust event processing with automatic retries, dead letter queues, and OpenTelemetry integration.

Features

  • Type-Safe: Full type hints and mypy compatibility
  • Consumer Groups: Built-in support for Redis consumer groups
  • Automatic Retries: Configurable retry logic with dead letter queue
  • Heartbeat Management: Automatic lease extension for long-running tasks
  • Telemetry: OpenTelemetry integration for metrics and tracing
  • Event Streaming: Optional event stream for progress tracking
  • Async/Await: Built on asyncio for high performance

Installation

pip install process-redis-events

For development:

pip install process-redis-events[dev]

Quick Start

import asyncio
from redis.asyncio import Redis
from process_redis_events import Stream, StartFrom

# Define your data type
from typing import TypedDict

class MyData(TypedDict):
    foo: str

# Create a stream
async def main():
    stream = Stream[MyData](
        name="my-stream",
        create_redis=lambda: Redis.from_url("redis://localhost"),
        produce_events=True
    )

    # Add data to the stream
    await stream.add({"foo": "bar"})

    # Process events
    async def process_item(item):
        print(f"Processing: {item.data}")
        # Your processing logic here

    await stream.process(
        options={
            "consumer_group": "my-group",
            "signal": asyncio.Event(),  # Use for graceful shutdown
        },
        callback=process_item
    )

asyncio.run(main())

Advanced Usage

With Data Transformation

from process_redis_events import QueueItem

async def transform(data_list: list[MyData]) -> list[dict]:
    return [{"bar": item["foo"]} for item in data_list]

async def process_item(item: QueueItem[dict]):
    print(f"Transformed data: {item.data}")
    await item.report_progress(0.5, "Halfway done")
    await item.report_progress(1.0, "Complete")

await stream.process(
    options={
        "consumer_group": "my-group",
        "map": transform,
        "signal": shutdown_event,
        "batch_size": 20,
        "concurrency": 10,
        "lease_ms": 30000,
    },
    callback=process_item
)

Error Handling and Retries

def should_retry(attempt: int, data: MyData) -> bool:
    # Retry up to 3 times
    return attempt < 3

await stream.process(
    options={
        "consumer_group": "my-group",
        "should_retry": should_retry,
        "signal": shutdown_event,
    },
    callback=process_item
)

API Reference

Stream[T]

Main class for processing Redis streams.

Constructor Parameters:

  • name: Stream name
  • create_redis: Factory function returning Redis client
  • produce_events: Enable event stream (default: False)
  • telemetry_config: Optional telemetry configuration

Methods:

  • add(data: T) -> dict: Add item to stream
  • process(options, callback): Process stream items
  • clear(): Clear stream data
  • get_stream_info(): Get stream statistics
  • get_consumer_groups_info(): Get consumer group info
  • create_event_stream(): Create event tracking stream

QueueItem[T]

Represents a queue item being processed.

Attributes:

  • id: Unique message ID
  • data: Message data (type T)
  • attempts: Number of processing attempts
  • report_progress: Async function to report progress

StartFrom

Enum for consumer group starting position:

  • StartFrom.OLDEST: Start from beginning
  • StartFrom.LATEST: Start from latest

Testing

# Run tests
pytest

# Run with coverage
pytest --cov=process_redis_events

# Type checking
mypy process_redis_events

License

ISC License - see LICENSE file for details

Contributing

Contributions welcome! Please ensure:

  • All tests pass
  • Code is type-checked with mypy
  • Code is formatted with black
  • Follow existing patterns and conventions

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

process_redis_events-5.0.4.tar.gz (38.3 kB view details)

Uploaded Source

Built Distribution

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

process_redis_events-5.0.4-py3-none-any.whl (17.4 kB view details)

Uploaded Python 3

File details

Details for the file process_redis_events-5.0.4.tar.gz.

File metadata

  • Download URL: process_redis_events-5.0.4.tar.gz
  • Upload date:
  • Size: 38.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for process_redis_events-5.0.4.tar.gz
Algorithm Hash digest
SHA256 cbcb2f9f35d6ebbe57267d06e1be086ff5a3854d47da10430d661decd40eaff3
MD5 f7380dc4a23b53c8480b36b3e92ece37
BLAKE2b-256 0a7f41f7887225fa02c9e4b2ea75d6dbb6282f9af4ddb0d0284158108194e37d

See more details on using hashes here.

File details

Details for the file process_redis_events-5.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for process_redis_events-5.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 1f6239bb5c6f68dceb959a19ddb283876670c4936429569406c0a28aba576166
MD5 3d85ef63ff21410e4aa587df571a4f73
BLAKE2b-256 2cca91cdfc8a0a5740fb3a2e31438c77e5e4d933db92d18930ccc28cd5f1d230

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