MCPcopy
hub / github.com/ag2ai/faststream

github.com/ag2ai/faststream @0.7.1 sqlite

repository ↗ · DeepWiki ↗ · release 0.7.1 ↗
7,057 symbols 39,383 edges 1,854 files 733 documented · 10%
README

FastStream

FastStream is an asynchronous Python framework for building event-driven applications. It brings together message broker integration, dependency injection, validation, testing utilities, and AsyncAPI documentation generation in a single toolkit, reducing boilerplate without hiding the capabilities of the underlying broker.


Trendshift

Test Passing Coverage Downloads Package version Supported Python versions\ CodeQL Dependency Review License Code of Conduct\ Discord FastStream Telegram\ Gurubase


Features

FastStream simplifies the process of writing producers and consumers for message queues, handling all the parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, FastStream simplifies your work while keeping the door open for more advanced use cases. Here's a look at the core features that make FastStream a go-to framework for modern, data-centric microservices.

  • Multiple Brokers: FastStream provides a suitable API to work across multiple message brokers (Kafka, RabbitMQ, NATS, Redis, MQTT support)

  • Built-in Serialization: Leverage Pydantic or Msgspec validation capabilities to serialize and validate incoming messages

  • Automatic Docs: Stay ahead with automatic AsyncAPI documentation

  • Intuitive: Full-typed editor support makes your development experience smooth, catching errors before they reach runtime

  • Powerful Dependency Injection System: Manage your service dependencies efficiently with FastStream's built-in DI system

  • Testable: Supports in-memory tests, making your CI/CD pipeline faster and more reliable

  • Extensible: Use extensions for lifespans, custom serialization and middleware

  • Integrations: FastStream is fully compatible with any HTTP framework you want (FastAPI especially)

That's FastStream in a nutshell - easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, FastStream has got you covered.


Documentation: https://faststream.ag2.ai/latest/

Table of Contents

Project History

FastStream is a package based on the ideas and experiences gained from FastKafka and Propan. By joining our forces, we picked up the best from both packages and created a unified way to write services capable of processing streamed data regardless of the underlying protocol.


Versioning Policy

FastStream has a stable public API. Only major updates may introduce breaking changes.

Prior to FastStream's 1.0 release, each minor update is considered a major and can introduce breaking changes, but these changes were communicated through two-versions deprecation warnings prior to being fully removed. So features deprecated in the 0.4 version were only removed in version 0.6.

Our team is working toward the stable 1.0 version.

Installation

FastStream works on Linux, macOS, Windows and most Unix-style operating systems. You can install it with pip as usual:

pip install 'faststream[kafka]'
# or
pip install 'faststream[confluent]'
# or
pip install 'faststream[rabbit]'
# or
pip install 'faststream[nats]'
# or
pip install 'faststream[redis]'
# or
pip install 'faststream[mqtt]'

Writing app code

FastStream brokers provide convenient function decorators @broker.subscriber and @broker.publisher to allow you to delegate the actual process of:

  • consuming and producing data to Event queues, and

  • decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, FastStream uses Pydantic to parse input JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using FastStream that consumes data from an incoming data stream and outputs the data to another one:

from faststream import FastStream
from faststream.kafka import KafkaBroker
# from faststream.confluent import KafkaBroker
# from faststream.rabbit import RabbitBroker
# from faststream.nats import NatsBroker
# from faststream.redis import RedisBroker
# from faststream.mqtt import MQTTBroker

broker = KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")
# broker = NatsBroker("nats://localhost:4222/")
# broker = RedisBroker("redis://localhost:6379/")
# broker = MQTTBroker("localhost")

app = FastStream(broker)

@broker.subscriber("in")
@broker.publisher("out")
async def handle_msg(user: str, user_id: int) -> str:
    return f"User: {user_id} - {user} registered"

Pydantic serialization

Also, Pydantic’s BaseModel class allows you to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

from pydantic import BaseModel, Field, PositiveInt
from faststream import FastStream
from faststream.kafka import KafkaBroker

broker = KafkaBroker("localhost:9092")
app = FastStream(broker)

class User(BaseModel):
    user: str = Field(..., examples=["John"])
    user_id: PositiveInt = Field(..., examples=["1"])

@broker.subscriber("in")
@broker.publisher("out")
async def handle_msg(data: User) -> str:
    return f"User: {data.user} - {data.user_id} registered"

By default we use PydanticV2 written in Rust as serialization library, but you can downgrade it manually, if your platform has no Rust support - FastStream will work correctly with PydanticV1 as well.

To choose the Pydantic version, you can install the required one using the regular

pip install pydantic==1.X.Y

FastStream (and FastDepends inside) should work correctly with almost any version.

Msgspec serialization

Moreover, FastStream is not tied to any specific serialization library, so you can use any preferred one. Fortunately, we provide a built‑in alternative for the most popular Pydantic replacement - Msgspec.

from fast_depends.msgspec import MsgSpecSerializer
from faststream.kafka import KafkaBroker

broker = KafkaBroker(serializer=MsgSpecSerializer())

You can read more about the feature in the documentation.

Unified API

At first glance, FastStream unifies various broker backends under a single API. However, a completely unified API inevitably results in missing features. We do not want to limit users' choices. If you prefer Kafka over Redis, there is a reason. Therefore, we support all native broker features you need.

Consequently, our unified API has a relatively limited scope:

from faststream.[broker] import [Broker], [Broker]Message

broker = [Broker](*servers)

@broker.subscriber([source])  # Kafka topic / RMQ queue / NATS subject / MQTT topic / etc
@broker.publisher([destination])  # topic / routing key / subject / etc
async def handler(msg: [Broker]Message) -> None:
    await msg.ack()  # control brokers' acknowledgement policy

...

await broker.publish("Message", [destiination])

Beyond this scope you can use any broker-native features you need:

  • Kafka - specific partition reads, partitioner control, consumer groups, batch processing, etc.
  • RabbitMQ - all exchange types, Redis Streams, RPC, manual channel configuration, DLQ, etc.
  • NATS - core and Push/Pull JetStream subscribers, KeyValue, ObjectStorage, RPC, etc.
  • Redis - Pub/Sub, List, Stream subscribers, consumer groups, acknowledgements, etc.
  • MQTT - topic subscriptions (including wildcards), QoS and retain, MQTT 3.1.1 and 5.0, request/reply (RPC), TLS, etc.

You can find detailed information about all supported features in FastStream’s broker‑specific documentation.

If a particular feature is missing or not yet supported, you can always fall back to the native broker client/connection for those operations.


Testing the service

The service can be tested using the TestBroker context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your subscriber and publisher decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:


import pytest
import pydantic
from faststream.kafka import TestKafkaBroker


@pytest.mark.asyncio
async def test_correct():
    async with TestKafkaBroker(broker) as br:
        await br.publish({
            "user": "John",
            "user_id": 1,
        }, "in")

@pytest.mark.asyncio
async def test_invalid():
    async with TestKafkaBroker(broker) as br:
        with pytest.raises(pydantic.ValidationError):
            await br.publish("wrong message", "in")

Running the application

The application can be started using built-in FastStream CLI command.

Before running the service, install FastStream CLI using the following command:

pip install "faststream[cli]"

To run the service, use the FastStream CLI command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

faststream run basic:app

After running the command, you should see the following output:

INFO     - FastStream app starting...
INFO     - input_data |            - `HandleMsg` waiting for messages
INFO     - FastStream app started successfully! To exit press CTRL+C

Also, FastStream provides you with a great hot reload feature to improve your Development Experience

faststream run basic:app --reload

And multiprocessing horizontal scaling feature as well:

faststream run basic:app --workers 3

You can learn more about CLI features here


Project Documentation

FastStream automatically generates documentation for your project according to the AsyncAPI specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you

Core symbols most depended-on inside this repo

start
called by 374
benchmarks/bench.py
get
called by 302
faststream/opentelemetry/baggage.py
set
called by 292
faststream/opentelemetry/baggage.py
to_jsonable
called by 242
faststream/specification/base/specification.py
include_router
called by 219
faststream/_internal/fastapi/router.py
get_subscriber_params
called by 188
tests/brokers/base/basic.py
Context
called by 168
faststream/params/params.py
publisher
called by 160
faststream/nats/fastapi/fastapi.py

Shape

Method 3,299
Function 2,252
Class 1,266
Route 240

Languages

Python100%
TypeScript1%

Modules by API surface

tests/brokers/base/middlewares.py64 symbols
tests/brokers/base/fastapi.py61 symbols
tests/mypy/nats.py58 symbols
tests/mypy/redis.py53 symbols
tests/mypy/kafka.py53 symbols
tests/brokers/redis/test_consume.py50 symbols
tests/asyncapi/base/v2_6_0/arguments.py50 symbols
tests/mypy/rabbit.py48 symbols
tests/brokers/redis/test_cluster_more_unit.py46 symbols
tests/asyncapi/base/v3_0_0/arguments.py46 symbols
tests/asyncapi/base/v2_6_0/naming.py40 symbols
tests/asyncapi/base/v3_0_0/naming.py39 symbols

Datastores touched

postgresDatabase · 1 repos

For agents

$ claude mcp add faststream \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact