Skip to main content

tRPC Kafka plugin

中文

Kafka for the tRPC-Python framework: a producer client, and consumers that run inside a tRPC server and hand each record to your servicer. The broker connection is aiokafka.

Install

Requirements: trpc-python, aiokafka.

pip3 install trpc-kafka

Import trpc_kafka before Server.serve(): the import registers the kafka protocol and the hooks that run the consumers.

Consume

Set protocol: kafka on a server service. target holds the brokers, then ?, then the consumer options as k=v&k=v. ip, port and network are not listened on; the consumers connect to the brokers.

server:
  service:
    - name: trpc.trpc-python.trpc-kafka.consume
      ip: 127.0.0.1
      port: 8000
      target: localhost:9092?topics=test-topic&group=test_consumers&enable_auto_commit=true
      network: tcp
      protocol: kafka
      timeout: 1000
from trpc_sdk.abc import TrpcContext
from trpc_sdk.server import create_server

import trpc_kafka


class KafkaServer(trpc_kafka.TrpcKafkaServicer):

    async def handle(self, ctx: TrpcContext, key, value, topic, partition, offset, timestamp):
        print(key, value, topic, partition, offset)


server = create_server("trpc_python.yaml")
trpc_kafka.register_trpc_kafka_server(server, KafkaServer())
server.serve()

For batches, add batch_num=<n> to the target and register a TrpcKafkaBatchConsumerServicer with register_trpc_kafka_batch_consumer_server; its handle(ctx, msgs) receives a list of ConsumerRecord. parallel_num splits a batch into key-stable groups that run concurrently, and msg_gather_timeout is the getmany timeout in milliseconds.

With enable_auto_commit=false, a record (or a batch) is committed after its handler returns. With auto-commit on, aiokafka commits every auto_commit_interval_ms.

Produce

client:
  service:
    - name: trpc.kafka.producer.service
      target: ip://localhost:9092?linger_ms=5
      protocol: kafka
      timeout: 1000
import trpc_kafka

client = trpc_kafka.Client("trpc.kafka.producer.service")


async def send(ctx):
    meta = await client.produce(ctx, "test-topic", "key", "value")
    print(meta.partition, meta.offset)

produce returns aiokafka's RecordMetadata. One producer is created per target and per event loop, because an AIOKafkaProducer only works on the loop that created it; handlers on different serving threads or processes each get their own. Inside a server, the producers of a serving loop are stopped (and their lingering records flushed) when the loop stops. A standalone script should call await trpc_kafka.client_transport.stop_producers_for_current_loop() before its loop ends.

Process and thread models

The process model comes from global.processmodel.

Every serving loop (an event loop that runs handlers) builds its own consumer for each Kafka service, all in the group of the service's target, and handles the records it fetches on that loop. Kafka then spreads the partitions over them.

Model global.processmodel Consumers per Kafka service Where
merge, single loop none (default) 1 the main loop
merge, threads single_process, handle_num: N N each serving thread
SeparateThread single_process, io_handle_type: separate, handle_num: N N each handle thread
separate multi_process, io_handle_type: separate, handle_num: N N each rpc task process; the I/O process has none
merge, processes multi_process, io_handle_type: merge, handle_num: N N each worker process

Give the topic at least as many partitions as there are consumers in the group; extra consumers get no partition and stay idle.

On SIGTERM each serving process stops fetching at once, lets the records already fetched finish during the drain (server.close_wait_time), commits them (with auto-commit off), stops its consumers so they leave the group, and then stops the producers of each serving loop.

Examples

examples/ has one config per model. How to run them, and what each config does, is in examples/README.md. The one-step script is examples/run_examples.sh.

Config Model
trpc_python.yaml merge, single loop
trpc_python_merge_threads.yaml merge, two serving threads
trpc_python_separate_thread.yaml one I/O thread, two handle threads
trpc_python_separate.yaml one I/O process, two rpc task processes
trpc_python_merge_processes.yaml two worker processes
cd examples
python trpc_main.py -c trpc_python_merge_threads.yaml          # add --batch to consume in batches
python kafka_client.py --num 200                               # produce 200 records with distinct keys
python test_service_rpc.py --num 50                            # SayHello, which produces from the handler

trpc_main.py serves the Kafka consumer and a Greeter whose SayHello produces to Kafka. Every consumed record is appended as one JSON line, with the pid and thread that handled it, to $TRPC_KAFKA_CONSUMED_LOG (/tmp/trpc_kafka_consumed.log by default).

Metadata

Release files for trpc-kafka-python 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for trpc-kafka-python 1.0.0
File Size Uploaded Provenance Actions
trpc_kafka_python-1.0.0.tar.gz 34.0 kB Without provenance Details for trpc_kafka_python-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for trpc-kafka-python 1.0.0
File Interpreter ABI Platform Actions
trpc_kafka_python-1.0.0-py3-none-any.whl Python 3 none any Details for trpc_kafka_python-1.0.0-py3-none-any.whl

Total release size: 62.6 kB

Release files / trpc_kafka_python-1.0.0.tar.gz

Download URL trpc_kafka_python-1.0.0.tar.gz
Size 34.0 kB
Tags Source
SHA-256 checksum
How to use checksums
8c70acb840ab8450975073b7af86236c7f9ca3994d0b5965c9445d3d20d13690
BLAKE2b-256 checksum
How to use checksums
c0266b54990666e0b18d14c55c877ac70e74e7388134ded324722881b3a7bb49
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / trpc_kafka_python-1.0.0-py3-none-any.whl

Download URL trpc_kafka_python-1.0.0-py3-none-any.whl
Size 28.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3883441efdc9dd7104b6b7cad0919120c05771c278df893e3df39be8226165f9
BLAKE2b-256 checksum
How to use checksums
973965611f59a62c09397a51945d6e7ecd97e2022d4a88d0b70687a26819882a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Security for trpc-kafka-python 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page