Skip to content

Subscription Types

Protean provides two subscription types for connecting handlers to message sources. Each is optimized for different use cases and provides different guarantees.

Overview

Feature StreamSubscription EventStoreSubscription
Message Source Redis Streams Event Store
Delivery Pattern Push (blocking read) Poll
Consumer Groups Yes No
Horizontal Scaling Yes Limited
Dead Letter Queue Yes Failed-position stream
Automatic Retries Yes Yes, in a periodic recovery pass
Position Tracking Redis (automatic) Event Store (manual)
Recommended For Production workloads Projections, replay, debugging

StreamSubscription

StreamSubscription uses Redis Streams with consumer groups for reliable, scalable message processing. This is the recommended subscription type for production workloads.

Note

Setting default_subscription_type = "stream" in your domain configuration automatically enables the transactional outbox. The outbox is required so that domain events committed to your database are reliably published to Redis Streams.

How It Works

Sequence diagram

Key Features

Consumer Groups

Multiple instances of your application can process messages in parallel:

Stream: orders
├── Consumer Group: OrderEventHandler
│   ├── Consumer: order-handler-host1-12345-abc123
│   ├── Consumer: order-handler-host2-12346-def456
│   └── Consumer: order-handler-host3-12347-ghi789

Each message is delivered to exactly one consumer in the group, enabling horizontal scaling.

Blocking Reads

StreamSubscription uses Redis's XREADGROUP with blocking, which means:

  • No CPU-intensive polling
  • Low latency - messages are delivered as soon as available
  • Configurable timeout for periodic maintenance (the Redis broker caps each wait at 1000 ms)
# fragment
# Internally uses blocking read
messages = broker.read_blocking(
    stream=stream_category,
    consumer_group=consumer_group,
    consumer_name=consumer_name,
    timeout_ms=5000,  # Redis caps the wait at 1 second
    limit=100,        # Read up to 100 messages
)

Dead Letter Queue

Failed messages are moved to a DLQ after exhausting retries:

Stream: orders
├── Main stream: orders (normal messages)
└── DLQ stream: orders:dlq (failed messages)

A DLQ message is the original message with a _dlq_metadata key added for debugging. consumer_group holds the handler's fully qualified name:

# fragment
{
    # ...the original message's keys...
    "_dlq_metadata": {
        "original_stream": "orders",
        "original_id": "1234567890-0",
        "consumer_group": "shop.handlers.OrderEventHandler",
        "consumer": "order-handler-host1-12345-abc123",
        "failed_at": "2024-01-15T10:30:00Z",
        "retry_count": 3,
    },
}
Managing DLQ Messages

Protean provides built-in tools to inspect and act on DLQ messages without writing custom scripts:

  • CLI: Use protean dlq to list, inspect, replay, or purge DLQ messages from the terminal.
  • Observatory: The DLQ tab in the Observatory dashboard provides a web UI and REST API (/api/dlq/*) for the same operations.

See Dead Letter Queue Management for usage examples.

Automatic Retries

Failed messages are automatically retried with configurable delays:

@domain.aggregate
class Order:
    total: Float(required=True)


@domain.event(part_of=Order)
class OrderPlaced:
    order_id: Identifier(required=True)
    total: Float(required=True)


@domain.event_handler(
    part_of=Order,
    subscription_type="stream",
    subscription_config={
        "max_retries": 3,
        "retry_delay_seconds": 1,
    },
)
class OrderEventHandler: ...

StreamSubscription Configuration Options

Option Default Description
messages_per_tick 100 Messages to read per batch
blocking_timeout_ms 100 Longest wait of an idle blocking read, in milliseconds. Must be positive. The Redis broker waits at most 1000 ms per read. A read returns as soon as a message arrives, so the value does not affect latency. With priority lanes on, the Redis broker waits on the primary and the backfill stream at once, and a message on either one ends the wait
max_retries 3 Retry attempts before moving to DLQ
retry_delay_seconds 1 Delay between retries
enable_dlq true Whether to use dead letter queue

Stream retention

After each batch, a StreamSubscription trims the stream it just read from. The broker removes only the entries that every consumer group on the stream has read and acknowledged. No setting controls the trim.

Each consumer group sets a bound. A group with pending entries (delivered but not yet acknowledged) keeps its oldest pending entry and everything after it. A group with no pending entries keeps the last entry it read and everything after it. The broker trims below the lowest bound across all groups, so no group that exists at trim time loses an entry it still needs, and a pending entry is still there when a retry or a claim reads it. A handler added later starts at the oldest entry left in the stream.

A consumer group that never reads keeps the whole stream. Its last-delivered position stays at 0-0, so it always holds the lowest bound, and the stream grows until you delete that group. This happens with a consumer that died before its first read. A handler you removed without deleting its group stops trimming in the same way, from the last entry that group read.

A stream with no consumer group is not trimmed. Trimming is approximate (Redis's ~): the broker removes whole nodes of entries, so the stream can stay a little above the bound. There is no time-based TTL.

Only a broker that declares STREAM_RETENTION, such as Redis Streams, trims. On any other broker the subscription does not call the trim.

When some handler declares sequential_by on a category and the broker partitions streams, every handler on that category runs on a partitioned subscription that reads per-key partition streams, whether or not it declares sequential_by itself. That subscription does not trim them.

When to Use

Use StreamSubscription when you need:

  • Production reliability: At-least-once delivery with DLQ
  • Horizontal scaling: Multiple consumers processing in parallel
  • Retry handling: Automatic retries for transient failures
  • Low latency: Blocking reads minimize delay

EventStoreSubscription

EventStoreSubscription reads messages directly from the event store. It's designed for scenarios where you need direct access to the event stream.

How It Works

Sequence diagram

Key Features

Direct Event Store Access

Reads events directly from the event store, preserving the complete event history:

# fragment
messages = event_store.read(
    stream_category,
    position=current_position + 1,
    limit=messages_per_tick,
)

Position Tracking

Position is stored in the event store itself as a special message type:

# fragment
# Position stream name
# subscriber_name is the handler's fully qualified class name
f"position-{subscriber_name}-{stream_category}"

# Stored as Read position message
{
    "data": {"position": 145},
    "metadata": {
        "headers": {"type": "Read"},
        "domain": {"kind": "READ_POSITION", "origin_stream": "orders"},
    },
}

Origin Stream Filtering

Filter messages by their origin stream. Use this filter when your handler processes events raised in response to specific commands:

@domain.event_handler(
    part_of=Order,
    source_stream="manage_order",  # Only events triggered by manage_order commands
)
class OrderEventHandler: ...

EventStoreSubscription Configuration Options

Option Default Description
messages_per_tick 100 Messages to read per batch
tick_interval 0 Seconds between polling cycles
position_update_interval 10 Messages between position writes
origin_stream None Filter by origin stream
max_tick_interval 1 Longest wait, in seconds, between reads while no new messages arrive. Domain-wide only, under [server.event_store_subscription]. 0 keeps the wait at tick_interval

An idle EventStoreSubscription waits longer between reads, so it does not query the event store in a tight loop. With tick_interval 0, it waits 10 ms after the first empty read. With a longer tick_interval, the wait doubles from tick_interval. Each further empty read doubles it again, up to max_tick_interval. A read that returns messages sets the wait back to tick_interval. On a category subscription, a read whose messages are all dropped by the origin_stream filter counts as empty. On a $all subscription, a read held at a gap counts as empty, and a read that moves the cursor counts as a read that returns messages. The cursor moves past snapshot rows, an abandoned gap, and messages the origin_stream filter drops. The backoff adds at most max_tick_interval seconds, or tick_interval seconds when that is longer, before the subscription reads a new message.

When to Use

Use EventStoreSubscription when you need:

  • Projections: Building read models from event history
  • Event replay: Reprocessing historical events
  • Debugging: Inspecting event flow in development
  • Single-worker scenarios: When horizontal scaling isn't needed

Production Warning

When using EventStoreSubscription in production, Protean logs a warning:

⚠️ EventStoreSubscription is being used in production.
For production workloads, consider using StreamSubscription which provides:
transactional outbox pattern, automatic retry mechanisms,
dead letter queue, and horizontal scaling with consumer groups.

This warning appears when PROTEAN_ENV, PYTHON_ENV, ENV, or ENVIRONMENT is set to production, prod, or prd.

Recommendation Summary

Scenario Recommended Type
Production event handlers StreamSubscription
Production command handlers StreamSubscription
Projections/read models EventStoreSubscription
Event replay EventStoreSubscription
Development/debugging Either (EventStoreSubscription simpler)
High-throughput processing StreamSubscription
Single-server deployment Either

Configuration Examples

Note

If you do not explicitly specify a subscription_type or subscription_profile, Protean uses the defaults from your domain configuration.

StreamSubscription Configuration

@domain.event_handler(
    part_of=Order,
    subscription_type="stream",
    subscription_config={
        "messages_per_tick": 100,
        "blocking_timeout_ms": 5000,
        "max_retries": 3,
        "retry_delay_seconds": 1,
        "enable_dlq": True,
    },
)
class OrderEventHandler: ...

Or using a profile:

@domain.event_handler(
    part_of=Order,
    subscription_profile="production",
)
class OrderEventHandler: ...

EventStoreSubscription Configuration

@domain.event_handler(
    part_of=Order,
    subscription_type="event_store",
    subscription_config={
        "messages_per_tick": 100,
        "tick_interval": 1,
        "position_update_interval": 10,
    },
)
class OrderEventHandler: ...

Or using a profile:

@domain.projection
class OrderSummary:
    order_id: Identifier(identifier=True)
    total: Float()


@domain.projector(
    projector_for=OrderSummary,
    aggregates=[Order],
    subscription_profile="projection",
)
class OrderProjector: ...

Monitoring lag

Both subscription types support lag monitoring through the CLI, Observatory API, and Prometheus metrics. Lag is computed differently for each type:

Type How lag is calculated
EventStoreSubscription category_head_position(category) - current_position where current_position is read from the handler's position-{subscriber}-{category} stream
StreamSubscription Redis XINFO GROUPS native lag field (Redis 7.0+). When Redis has no lag to report (before 7.0, or when it sends nil), the messages after last-delivered-id are counted with XRANGE

Check subscription lag from the CLI:

protean subscriptions status --domain=my_app

Or query the Observatory:

curl http://localhost:9000/api/subscriptions

See protean subscriptions for full CLI documentation and Observability for the Observatory API.

  • Configuration: Learn about configuration profiles and the priority hierarchy
  • Outbox Pattern: Understand how StreamSubscription uses the transactional outbox