Repository files navigation

TinyStream

TinyStream is a lightweight streaming engine in Python, inspired by Apache Kafka.

Features

  • Append-only Partitioned Log: The core storage mechanism.
  • Segment-Based Storage: Logs are broken into segments with sparse .index files for fast, efficient reads.
  • Pluggable Storage: Supports SingleLogStorage (one file) or SegmentedLogStorage (retention-ready).
  • Controller Cluster: A controller-based architecture (no "single mode") manages cluster state.
  • Metadata & Liveness: The Controller tracks broker liveness (via heartbeats) and partition assignments.
  • Leader Election: The Controller automatically elects new leaders when brokers fail
  • Producer/Consumer APIs: Asynchronous clients for producing and consuming data.
  • Log Retention: Supports per-topic log retention by time (retention_ms) or size (retention_bytes)
  • HTTP Admin Dashboard: A built-in, lightweight web UI (via FastAPI) to view cluster status.

Configuration Management

TinyStream uses a 4-layer "override" system for configuration, managed by the ConfigManager.

The final value for any setting is chosen in this order of priority:

  • CLI Arguments: (e.g., --controller-uri)
  • Environment Variables: (e.g., TINYSTREAM_CONTROLLER_URI)
  • User-Provided Config File: (e.g., --config test_confs/broker-1.ini)
  • Default Component Config File: (e.g., tinystream/config/controller.ini)

This allows you to have a set of default configs and override them at runtime. For example, you can start a broker and tell it where the controller is via an environment variable, rather than modifying its config file.

Installation

The project uses uv for dependency management and execution.

  1. Clone the repository:
    git clone [https://github.com/Olamyy/tinystream](https://github.com/Olamyy/tinystream)
    cd tinystream
  2. Install the required dependencies:
    uv install

Quick Start: Running Locally

Here is how to run a minimal "cluster" (one controller, one broker) on your machine.

Step 1: Start the Controller

The Controller manages cluster metadata (topics, brokers, partition leaders).

uv run python -m tinystream.controller

The controller will start:

  • Its RPC Server on localhost:9093 (for Brokers to connect).
  • The Metastore API / Dashboard on http://localhost:3200.

Step 2: Start a Broker

The Broker stores data. This command will load tinystream/config/broker.ini (which knows the controller's address) and start the broker with ID 1.

uv run python -m tinystream.broker --broker-id 1

The broker will start:

  • Its RPC Server on localhost:9095 (from broker.ini, for clients).
  • It will then connect to the Controller at localhost:9093 to register itself.

Step 4: Create a Topic

Use the admin client to tell the Controller to create a new topic.

uv run python -m tinystream.admin create-topic \
--topic "events" \
--partitions 3 \
--replication-factor 1 \
--metastore "localhost:6000"

Step 5: Produce Messages

importasyncioimportargparsefromtinystream.client.producerimportProducerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
producer=Producer(config=config)
try:
awaitproducer.connect()
print("Producer connected. Sending 10 messages...")
foriinrange(10):
msg=f"hello-tinystream-{i}"key=f"user-{i%2}"print(f"Sending: {msg} (key: {key})")
response=awaitproducer.send("events", msg.encode('utf-8'), key=key)
print(f"-> Broker response: {response}")
awaitasyncio.sleep(0.5)
exceptExceptionase:
print(f"Error: {e}")
finally:
awaitproducer.close()
if__name__=="__main__":
asyncio.run(run())

Step 6: Consume Messages

importasyncioimportargparsefromtinystream.client.consumerimportConsumerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
consumer=Consumer(config=config, group_id="my-test-group")
try:
awaitconsumer.connect()
print("Consumer connected.")
consumer.assign(topic="events", partition=0, start_offset=0)
print("Consuming from 'events-0'. Press Ctrl+C to stop.")
whileTrue:
messages=awaitconsumer.poll(max_messages=5)
ifmessages:
formsginmessages:
print(f"Received: {msg.decode('utf-8')}")
awaitconsumer.commit()
awaitasyncio.sleep(1)
exceptKeyboardInterrupt:
print("\nStopping consumer...")
finally:
awaitconsumer.close()
if__name__=="__main__":
asyncio.run(run())

Load Testing

A load test script is included in load_test.py. It uses spawns worker tasks to send data in parallel.

Before running, ensure the topic exists:

uv run python -m tinystream.admin create-topic --topic "load_test" --partitions 3 --replication-factor 1

To run the test for 60 seconds with 50 concurrent workers:

uv run python load_test.py \
--topic "load_test" \
--num-workers 50 \
--message-size 1024 \
--run-time 60

Load Test Results

TODO: Add results from a benchmark run (e.g., on an M4 Mac with 36GB memory) here.

Running Components in Isolation

For quick testing, each core component can be run in isolation directly as a module:

  • Controller: uv run python -m tinystream.controller
  • Broker: uv run python -m tinystream.broker
  • Producer: uv run python -m tinystream.client.producer
  • Consumer: uv run python -m tinystream.client.consumer
  • Admin: uv run python -m tinystream.client.admin

Architecture Overview

TinyStream is split into five layers:

┌────────────────────────────────────────────┐
│ Producers / Consumers │
│ • Send and fetch records from topics │
│ • Commit offsets │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Broker │
│ • Accepts produce/fetch requests │
│ • Manages topic partitions │
│ • Serves leader/follower replicas │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Partition │
│ • Manages append-only log segments |
│ • Handles retention and compaction │
│ • Stores offset and time indexes │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Segment │
│ • File-based, append-only structure │
│ • Supports batch reads via index lookups │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Storage │
│ • Local disk or tiered storage backend │
│ • Retention + compaction policy engine │
└────────────────────────────────────────────┘

Each topic is split into partitions, and each partition is an append-only log. Brokers host one or more partitions; producers and consumers talk to brokers via lightweight RPC.

Partition Storage Layout

Each partition is stored on disk as a directory containing segment and index files:

data/
└── topics/
└── user_clicks/
└── partition-0/
├── 00000000000000000000.log
├── 00000000000000000000.index
├── 00000000000001000000.log
├── 00000000000001000000.index
├── partition.metadata
└── lock

Messages are never deleted after consumption — instead, TinyStream enforces a retention policy (by time or size) to delete or compact old segments.

What to Test

CategoryExample
ReplicationWrite to leader → restart follower → verify catch-up
Leader ElectionKill leader → ensure controller reassigns
RetentionConfigure short TTL → check old segment deletion
ConsistencyCompare offsets after recovery
Consumer GroupsAdd/remove consumers → verify rebalancing

About

A lightweight streaming engine.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

TinyStream

TinyStream is a lightweight streaming engine in Python, inspired by Apache Kafka.

Features

  • Append-only Partitioned Log: The core storage mechanism.
  • Segment-Based Storage: Logs are broken into segments with sparse .index files for fast, efficient reads.
  • Pluggable Storage: Supports SingleLogStorage (one file) or SegmentedLogStorage (retention-ready).
  • Controller Cluster: A controller-based architecture (no "single mode") manages cluster state.
  • Metadata & Liveness: The Controller tracks broker liveness (via heartbeats) and partition assignments.
  • Leader Election: The Controller automatically elects new leaders when brokers fail
  • Producer/Consumer APIs: Asynchronous clients for producing and consuming data.
  • Log Retention: Supports per-topic log retention by time (retention_ms) or size (retention_bytes)
  • HTTP Admin Dashboard: A built-in, lightweight web UI (via FastAPI) to view cluster status.

Configuration Management

TinyStream uses a 4-layer "override" system for configuration, managed by the ConfigManager.

The final value for any setting is chosen in this order of priority:

  • CLI Arguments: (e.g., --controller-uri)
  • Environment Variables: (e.g., TINYSTREAM_CONTROLLER_URI)
  • User-Provided Config File: (e.g., --config test_confs/broker-1.ini)
  • Default Component Config File: (e.g., tinystream/config/controller.ini)

This allows you to have a set of default configs and override them at runtime. For example, you can start a broker and tell it where the controller is via an environment variable, rather than modifying its config file.

Installation

The project uses uv for dependency management and execution.

  1. Clone the repository:
    git clone [https://github.com/Olamyy/tinystream](https://github.com/Olamyy/tinystream)
    cd tinystream
  2. Install the required dependencies:
    uv install

Quick Start: Running Locally

Here is how to run a minimal "cluster" (one controller, one broker) on your machine.

Step 1: Start the Controller

The Controller manages cluster metadata (topics, brokers, partition leaders).

uv run python -m tinystream.controller

The controller will start:

  • Its RPC Server on localhost:9093 (for Brokers to connect).
  • The Metastore API / Dashboard on http://localhost:3200.

Step 2: Start a Broker

The Broker stores data. This command will load tinystream/config/broker.ini (which knows the controller's address) and start the broker with ID 1.

uv run python -m tinystream.broker --broker-id 1

The broker will start:

  • Its RPC Server on localhost:9095 (from broker.ini, for clients).
  • It will then connect to the Controller at localhost:9093 to register itself.

Step 4: Create a Topic

Use the admin client to tell the Controller to create a new topic.

uv run python -m tinystream.admin create-topic \
--topic "events" \
--partitions 3 \
--replication-factor 1 \
--metastore "localhost:6000"

Step 5: Produce Messages

importasyncioimportargparsefromtinystream.client.producerimportProducerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
producer=Producer(config=config)
try:
awaitproducer.connect()
print("Producer connected. Sending 10 messages...")
foriinrange(10):
msg=f"hello-tinystream-{i}"key=f"user-{i%2}"print(f"Sending: {msg} (key: {key})")
response=awaitproducer.send("events", msg.encode('utf-8'), key=key)
print(f"-> Broker response: {response}")
awaitasyncio.sleep(0.5)
exceptExceptionase:
print(f"Error: {e}")
finally:
awaitproducer.close()
if__name__=="__main__":
asyncio.run(run())

Step 6: Consume Messages

importasyncioimportargparsefromtinystream.client.consumerimportConsumerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
consumer=Consumer(config=config, group_id="my-test-group")
try:
awaitconsumer.connect()
print("Consumer connected.")
consumer.assign(topic="events", partition=0, start_offset=0)
print("Consuming from 'events-0'. Press Ctrl+C to stop.")
whileTrue:
messages=awaitconsumer.poll(max_messages=5)
ifmessages:
formsginmessages:
print(f"Received: {msg.decode('utf-8')}")
awaitconsumer.commit()
awaitasyncio.sleep(1)
exceptKeyboardInterrupt:
print("\nStopping consumer...")
finally:
awaitconsumer.close()
if__name__=="__main__":
asyncio.run(run())

Load Testing

A load test script is included in load_test.py. It uses spawns worker tasks to send data in parallel.

Before running, ensure the topic exists:

uv run python -m tinystream.admin create-topic --topic "load_test" --partitions 3 --replication-factor 1

To run the test for 60 seconds with 50 concurrent workers:

uv run python load_test.py \
--topic "load_test" \
--num-workers 50 \
--message-size 1024 \
--run-time 60

Load Test Results

TODO: Add results from a benchmark run (e.g., on an M4 Mac with 36GB memory) here.

Running Components in Isolation

For quick testing, each core component can be run in isolation directly as a module:

  • Controller: uv run python -m tinystream.controller
  • Broker: uv run python -m tinystream.broker
  • Producer: uv run python -m tinystream.client.producer
  • Consumer: uv run python -m tinystream.client.consumer
  • Admin: uv run python -m tinystream.client.admin

Architecture Overview

TinyStream is split into five layers:

┌────────────────────────────────────────────┐
│ Producers / Consumers │
│ • Send and fetch records from topics │
│ • Commit offsets │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Broker │
│ • Accepts produce/fetch requests │
│ • Manages topic partitions │
│ • Serves leader/follower replicas │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Partition │
│ • Manages append-only log segments |
│ • Handles retention and compaction │
│ • Stores offset and time indexes │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Segment │
│ • File-based, append-only structure │
│ • Supports batch reads via index lookups │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Storage │
│ • Local disk or tiered storage backend │
│ • Retention + compaction policy engine │
└────────────────────────────────────────────┘

Each topic is split into partitions, and each partition is an append-only log. Brokers host one or more partitions; producers and consumers talk to brokers via lightweight RPC.

Partition Storage Layout

Each partition is stored on disk as a directory containing segment and index files:

data/
└── topics/
└── user_clicks/
└── partition-0/
├── 00000000000000000000.log
├── 00000000000000000000.index
├── 00000000000001000000.log
├── 00000000000001000000.index
├── partition.metadata
└── lock

Messages are never deleted after consumption — instead, TinyStream enforces a retention policy (by time or size) to delete or compact old segments.

What to Test

CategoryExample
ReplicationWrite to leader → restart follower → verify catch-up
Leader ElectionKill leader → ensure controller reassigns
RetentionConfigure short TTL → check old segment deletion
ConsistencyCompare offsets after recovery
Consumer GroupsAdd/remove consumers → verify rebalancing

About

A lightweight streaming engine.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TinyStream

TinyStream is a lightweight streaming engine in Python, inspired by Apache Kafka.

Features

  • Append-only Partitioned Log: The core storage mechanism.
  • Segment-Based Storage: Logs are broken into segments with sparse .index files for fast, efficient reads.
  • Pluggable Storage: Supports SingleLogStorage (one file) or SegmentedLogStorage (retention-ready).
  • Controller Cluster: A controller-based architecture (no "single mode") manages cluster state.
  • Metadata & Liveness: The Controller tracks broker liveness (via heartbeats) and partition assignments.
  • Leader Election: The Controller automatically elects new leaders when brokers fail
  • Producer/Consumer APIs: Asynchronous clients for producing and consuming data.
  • Log Retention: Supports per-topic log retention by time (retention_ms) or size (retention_bytes)
  • HTTP Admin Dashboard: A built-in, lightweight web UI (via FastAPI) to view cluster status.

Configuration Management

TinyStream uses a 4-layer "override" system for configuration, managed by the ConfigManager.

The final value for any setting is chosen in this order of priority:

  • CLI Arguments: (e.g., --controller-uri)
  • Environment Variables: (e.g., TINYSTREAM_CONTROLLER_URI)
  • User-Provided Config File: (e.g., --config test_confs/broker-1.ini)
  • Default Component Config File: (e.g., tinystream/config/controller.ini)

This allows you to have a set of default configs and override them at runtime. For example, you can start a broker and tell it where the controller is via an environment variable, rather than modifying its config file.

Installation

The project uses uv for dependency management and execution.

  1. Clone the repository:
    git clone [https://github.com/Olamyy/tinystream](https://github.com/Olamyy/tinystream)
    cd tinystream
  2. Install the required dependencies:
    uv install

Quick Start: Running Locally

Here is how to run a minimal "cluster" (one controller, one broker) on your machine.

Step 1: Start the Controller

The Controller manages cluster metadata (topics, brokers, partition leaders).

uv run python -m tinystream.controller

The controller will start:

  • Its RPC Server on localhost:9093 (for Brokers to connect).
  • The Metastore API / Dashboard on http://localhost:3200.

Step 2: Start a Broker

The Broker stores data. This command will load tinystream/config/broker.ini (which knows the controller's address) and start the broker with ID 1.

uv run python -m tinystream.broker --broker-id 1

The broker will start:

  • Its RPC Server on localhost:9095 (from broker.ini, for clients).
  • It will then connect to the Controller at localhost:9093 to register itself.

Step 4: Create a Topic

Use the admin client to tell the Controller to create a new topic.

uv run python -m tinystream.admin create-topic \
--topic "events" \
--partitions 3 \
--replication-factor 1 \
--metastore "localhost:6000"

Step 5: Produce Messages

importasyncioimportargparsefromtinystream.client.producerimportProducerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
producer=Producer(config=config)
try:
awaitproducer.connect()
print("Producer connected. Sending 10 messages...")
foriinrange(10):
msg=f"hello-tinystream-{i}"key=f"user-{i%2}"print(f"Sending: {msg} (key: {key})")
response=awaitproducer.send("events", msg.encode('utf-8'), key=key)
print(f"-> Broker response: {response}")
awaitasyncio.sleep(0.5)
exceptExceptionase:
print(f"Error: {e}")
finally:
awaitproducer.close()
if__name__=="__main__":
asyncio.run(run())

Step 6: Consume Messages

importasyncioimportargparsefromtinystream.client.consumerimportConsumerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
consumer=Consumer(config=config, group_id="my-test-group")
try:
awaitconsumer.connect()
print("Consumer connected.")
consumer.assign(topic="events", partition=0, start_offset=0)
print("Consuming from 'events-0'. Press Ctrl+C to stop.")
whileTrue:
messages=awaitconsumer.poll(max_messages=5)
ifmessages:
formsginmessages:
print(f"Received: {msg.decode('utf-8')}")
awaitconsumer.commit()
awaitasyncio.sleep(1)
exceptKeyboardInterrupt:
print("\nStopping consumer...")
finally:
awaitconsumer.close()
if__name__=="__main__":
asyncio.run(run())

Load Testing

A load test script is included in load_test.py. It uses spawns worker tasks to send data in parallel.

Before running, ensure the topic exists:

uv run python -m tinystream.admin create-topic --topic "load_test" --partitions 3 --replication-factor 1

To run the test for 60 seconds with 50 concurrent workers:

uv run python load_test.py \
--topic "load_test" \
--num-workers 50 \
--message-size 1024 \
--run-time 60

Load Test Results

TODO: Add results from a benchmark run (e.g., on an M4 Mac with 36GB memory) here.

Running Components in Isolation

For quick testing, each core component can be run in isolation directly as a module:

  • Controller: uv run python -m tinystream.controller
  • Broker: uv run python -m tinystream.broker
  • Producer: uv run python -m tinystream.client.producer
  • Consumer: uv run python -m tinystream.client.consumer
  • Admin: uv run python -m tinystream.client.admin

Architecture Overview

TinyStream is split into five layers:

┌────────────────────────────────────────────┐
│ Producers / Consumers │
│ • Send and fetch records from topics │
│ • Commit offsets │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Broker │
│ • Accepts produce/fetch requests │
│ • Manages topic partitions │
│ • Serves leader/follower replicas │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Partition │
│ • Manages append-only log segments |
│ • Handles retention and compaction │
│ • Stores offset and time indexes │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Segment │
│ • File-based, append-only structure │
│ • Supports batch reads via index lookups │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Storage │
│ • Local disk or tiered storage backend │
│ • Retention + compaction policy engine │
└────────────────────────────────────────────┘

Each topic is split into partitions, and each partition is an append-only log. Brokers host one or more partitions; producers and consumers talk to brokers via lightweight RPC.

Partition Storage Layout

Each partition is stored on disk as a directory containing segment and index files:

data/
└── topics/
└── user_clicks/
└── partition-0/
├── 00000000000000000000.log
├── 00000000000000000000.index
├── 00000000000001000000.log
├── 00000000000001000000.index
├── partition.metadata
└── lock

Messages are never deleted after consumption — instead, TinyStream enforces a retention policy (by time or size) to delete or compact old segments.

What to Test

CategoryExample
ReplicationWrite to leader → restart follower → verify catch-up
Leader ElectionKill leader → ensure controller reassigns
RetentionConfigure short TTL → check old segment deletion
ConsistencyCompare offsets after recovery
Consumer GroupsAdd/remove consumers → verify rebalancing

About

A lightweight streaming engine.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TinyStream

TinyStream is a lightweight streaming engine in Python, inspired by Apache Kafka.

Features

  • Append-only Partitioned Log: The core storage mechanism.
  • Segment-Based Storage: Logs are broken into segments with sparse .index files for fast, efficient reads.
  • Pluggable Storage: Supports SingleLogStorage (one file) or SegmentedLogStorage (retention-ready).
  • Controller Cluster: A controller-based architecture (no "single mode") manages cluster state.
  • Metadata & Liveness: The Controller tracks broker liveness (via heartbeats) and partition assignments.
  • Leader Election: The Controller automatically elects new leaders when brokers fail
  • Producer/Consumer APIs: Asynchronous clients for producing and consuming data.
  • Log Retention: Supports per-topic log retention by time (retention_ms) or size (retention_bytes)
  • HTTP Admin Dashboard: A built-in, lightweight web UI (via FastAPI) to view cluster status.

Configuration Management

TinyStream uses a 4-layer "override" system for configuration, managed by the ConfigManager.

The final value for any setting is chosen in this order of priority:

  • CLI Arguments: (e.g., --controller-uri)
  • Environment Variables: (e.g., TINYSTREAM_CONTROLLER_URI)
  • User-Provided Config File: (e.g., --config test_confs/broker-1.ini)
  • Default Component Config File: (e.g., tinystream/config/controller.ini)

This allows you to have a set of default configs and override them at runtime. For example, you can start a broker and tell it where the controller is via an environment variable, rather than modifying its config file.

Installation

The project uses uv for dependency management and execution.

  1. Clone the repository:
    git clone [https://github.com/Olamyy/tinystream](https://github.com/Olamyy/tinystream)
    cd tinystream
  2. Install the required dependencies:
    uv install

Quick Start: Running Locally

Here is how to run a minimal "cluster" (one controller, one broker) on your machine.

Step 1: Start the Controller

The Controller manages cluster metadata (topics, brokers, partition leaders).

uv run python -m tinystream.controller

The controller will start:

  • Its RPC Server on localhost:9093 (for Brokers to connect).
  • The Metastore API / Dashboard on http://localhost:3200.

Step 2: Start a Broker

The Broker stores data. This command will load tinystream/config/broker.ini (which knows the controller's address) and start the broker with ID 1.

uv run python -m tinystream.broker --broker-id 1

The broker will start:

  • Its RPC Server on localhost:9095 (from broker.ini, for clients).
  • It will then connect to the Controller at localhost:9093 to register itself.

Step 4: Create a Topic

Use the admin client to tell the Controller to create a new topic.

uv run python -m tinystream.admin create-topic \
--topic "events" \
--partitions 3 \
--replication-factor 1 \
--metastore "localhost:6000"

Step 5: Produce Messages

importasyncioimportargparsefromtinystream.client.producerimportProducerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
producer=Producer(config=config)
try:
awaitproducer.connect()
print("Producer connected. Sending 10 messages...")
foriinrange(10):
msg=f"hello-tinystream-{i}"key=f"user-{i%2}"print(f"Sending: {msg} (key: {key})")
response=awaitproducer.send("events", msg.encode('utf-8'), key=key)
print(f"-> Broker response: {response}")
awaitasyncio.sleep(0.5)
exceptExceptionase:
print(f"Error: {e}")
finally:
awaitproducer.close()
if__name__=="__main__":
asyncio.run(run())

Step 6: Consume Messages

importasyncioimportargparsefromtinystream.client.consumerimportConsumerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
consumer=Consumer(config=config, group_id="my-test-group")
try:
awaitconsumer.connect()
print("Consumer connected.")
consumer.assign(topic="events", partition=0, start_offset=0)
print("Consuming from 'events-0'. Press Ctrl+C to stop.")
whileTrue:
messages=awaitconsumer.poll(max_messages=5)
ifmessages:
formsginmessages:
print(f"Received: {msg.decode('utf-8')}")
awaitconsumer.commit()
awaitasyncio.sleep(1)
exceptKeyboardInterrupt:
print("\nStopping consumer...")
finally:
awaitconsumer.close()
if__name__=="__main__":
asyncio.run(run())

Load Testing

A load test script is included in load_test.py. It uses spawns worker tasks to send data in parallel.

Before running, ensure the topic exists:

uv run python -m tinystream.admin create-topic --topic "load_test" --partitions 3 --replication-factor 1

To run the test for 60 seconds with 50 concurrent workers:

uv run python load_test.py \
--topic "load_test" \
--num-workers 50 \
--message-size 1024 \
--run-time 60

Load Test Results

TODO: Add results from a benchmark run (e.g., on an M4 Mac with 36GB memory) here.

Running Components in Isolation

For quick testing, each core component can be run in isolation directly as a module:

  • Controller: uv run python -m tinystream.controller
  • Broker: uv run python -m tinystream.broker
  • Producer: uv run python -m tinystream.client.producer
  • Consumer: uv run python -m tinystream.client.consumer
  • Admin: uv run python -m tinystream.client.admin

Architecture Overview

TinyStream is split into five layers:

┌────────────────────────────────────────────┐
│ Producers / Consumers │
│ • Send and fetch records from topics │
│ • Commit offsets │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Broker │
│ • Accepts produce/fetch requests │
│ • Manages topic partitions │
│ • Serves leader/follower replicas │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Partition │
│ • Manages append-only log segments |
│ • Handles retention and compaction │
│ • Stores offset and time indexes │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Segment │
│ • File-based, append-only structure │
│ • Supports batch reads via index lookups │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Storage │
│ • Local disk or tiered storage backend │
│ • Retention + compaction policy engine │
└────────────────────────────────────────────┘

Each topic is split into partitions, and each partition is an append-only log. Brokers host one or more partitions; producers and consumers talk to brokers via lightweight RPC.

Partition Storage Layout

Each partition is stored on disk as a directory containing segment and index files:

data/
└── topics/
└── user_clicks/
└── partition-0/
├── 00000000000000000000.log
├── 00000000000000000000.index
├── 00000000000001000000.log
├── 00000000000001000000.index
├── partition.metadata
└── lock

Messages are never deleted after consumption — instead, TinyStream enforces a retention policy (by time or size) to delete or compact old segments.

What to Test

CategoryExample
ReplicationWrite to leader → restart follower → verify catch-up
Leader ElectionKill leader → ensure controller reassigns
RetentionConfigure short TTL → check old segment deletion
ConsistencyCompare offsets after recovery
Consumer GroupsAdd/remove consumers → verify rebalancing

About

A lightweight streaming engine.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

TinyStream

TinyStream is a lightweight streaming engine in Python, inspired by Apache Kafka.

Features

  • Append-only Partitioned Log: The core storage mechanism.
  • Segment-Based Storage: Logs are broken into segments with sparse .index files for fast, efficient reads.
  • Pluggable Storage: Supports SingleLogStorage (one file) or SegmentedLogStorage (retention-ready).
  • Controller Cluster: A controller-based architecture (no "single mode") manages cluster state.
  • Metadata & Liveness: The Controller tracks broker liveness (via heartbeats) and partition assignments.
  • Leader Election: The Controller automatically elects new leaders when brokers fail
  • Producer/Consumer APIs: Asynchronous clients for producing and consuming data.
  • Log Retention: Supports per-topic log retention by time (retention_ms) or size (retention_bytes)
  • HTTP Admin Dashboard: A built-in, lightweight web UI (via FastAPI) to view cluster status.

Configuration Management

TinyStream uses a 4-layer "override" system for configuration, managed by the ConfigManager.

The final value for any setting is chosen in this order of priority:

  • CLI Arguments: (e.g., --controller-uri)
  • Environment Variables: (e.g., TINYSTREAM_CONTROLLER_URI)
  • User-Provided Config File: (e.g., --config test_confs/broker-1.ini)
  • Default Component Config File: (e.g., tinystream/config/controller.ini)

This allows you to have a set of default configs and override them at runtime. For example, you can start a broker and tell it where the controller is via an environment variable, rather than modifying its config file.

Installation

The project uses uv for dependency management and execution.

  1. Clone the repository:
    git clone [https://github.com/Olamyy/tinystream](https://github.com/Olamyy/tinystream)
    cd tinystream
  2. Install the required dependencies:
    uv install

Quick Start: Running Locally

Here is how to run a minimal "cluster" (one controller, one broker) on your machine.

Step 1: Start the Controller

The Controller manages cluster metadata (topics, brokers, partition leaders).

uv run python -m tinystream.controller

The controller will start:

  • Its RPC Server on localhost:9093 (for Brokers to connect).
  • The Metastore API / Dashboard on http://localhost:3200.

Step 2: Start a Broker

The Broker stores data. This command will load tinystream/config/broker.ini (which knows the controller's address) and start the broker with ID 1.

uv run python -m tinystream.broker --broker-id 1

The broker will start:

  • Its RPC Server on localhost:9095 (from broker.ini, for clients).
  • It will then connect to the Controller at localhost:9093 to register itself.

Step 4: Create a Topic

Use the admin client to tell the Controller to create a new topic.

uv run python -m tinystream.admin create-topic \
--topic "events" \
--partitions 3 \
--replication-factor 1 \
--metastore "localhost:6000"

Step 5: Produce Messages

importasyncioimportargparsefromtinystream.client.producerimportProducerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
producer=Producer(config=config)
try:
awaitproducer.connect()
print("Producer connected. Sending 10 messages...")
foriinrange(10):
msg=f"hello-tinystream-{i}"key=f"user-{i%2}"print(f"Sending: {msg} (key: {key})")
response=awaitproducer.send("events", msg.encode('utf-8'), key=key)
print(f"-> Broker response: {response}")
awaitasyncio.sleep(0.5)
exceptExceptionase:
print(f"Error: {e}")
finally:
awaitproducer.close()
if__name__=="__main__":
asyncio.run(run())

Step 6: Consume Messages

importasyncioimportargparsefromtinystream.client.consumerimportConsumerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
consumer=Consumer(config=config, group_id="my-test-group")
try:
awaitconsumer.connect()
print("Consumer connected.")
consumer.assign(topic="events", partition=0, start_offset=0)
print("Consuming from 'events-0'. Press Ctrl+C to stop.")
whileTrue:
messages=awaitconsumer.poll(max_messages=5)
ifmessages:
formsginmessages:
print(f"Received: {msg.decode('utf-8')}")
awaitconsumer.commit()
awaitasyncio.sleep(1)
exceptKeyboardInterrupt:
print("\nStopping consumer...")
finally:
awaitconsumer.close()
if__name__=="__main__":
asyncio.run(run())

Load Testing

A load test script is included in load_test.py. It uses spawns worker tasks to send data in parallel.

Before running, ensure the topic exists:

uv run python -m tinystream.admin create-topic --topic "load_test" --partitions 3 --replication-factor 1

To run the test for 60 seconds with 50 concurrent workers:

uv run python load_test.py \
--topic "load_test" \
--num-workers 50 \
--message-size 1024 \
--run-time 60

Load Test Results

TODO: Add results from a benchmark run (e.g., on an M4 Mac with 36GB memory) here.

Running Components in Isolation

For quick testing, each core component can be run in isolation directly as a module:

  • Controller: uv run python -m tinystream.controller
  • Broker: uv run python -m tinystream.broker
  • Producer: uv run python -m tinystream.client.producer
  • Consumer: uv run python -m tinystream.client.consumer
  • Admin: uv run python -m tinystream.client.admin

Architecture Overview

TinyStream is split into five layers:

┌────────────────────────────────────────────┐
│ Producers / Consumers │
│ • Send and fetch records from topics │
│ • Commit offsets │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Broker │
│ • Accepts produce/fetch requests │
│ • Manages topic partitions │
│ • Serves leader/follower replicas │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Partition │
│ • Manages append-only log segments |
│ • Handles retention and compaction │
│ • Stores offset and time indexes │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Segment │
│ • File-based, append-only structure │
│ • Supports batch reads via index lookups │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Storage │
│ • Local disk or tiered storage backend │
│ • Retention + compaction policy engine │
└────────────────────────────────────────────┘

Each topic is split into partitions, and each partition is an append-only log. Brokers host one or more partitions; producers and consumers talk to brokers via lightweight RPC.

Partition Storage Layout

Each partition is stored on disk as a directory containing segment and index files:

data/
└── topics/
└── user_clicks/
└── partition-0/
├── 00000000000000000000.log
├── 00000000000000000000.index
├── 00000000000001000000.log
├── 00000000000001000000.index
├── partition.metadata
└── lock

Messages are never deleted after consumption — instead, TinyStream enforces a retention policy (by time or size) to delete or compact old segments.

What to Test

CategoryExample
ReplicationWrite to leader → restart follower → verify catch-up
Leader ElectionKill leader → ensure controller reassigns
RetentionConfigure short TTL → check old segment deletion
ConsistencyCompare offsets after recovery
Consumer GroupsAdd/remove consumers → verify rebalancing

About

A lightweight streaming engine.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TinyStream

TinyStream is a lightweight streaming engine in Python, inspired by Apache Kafka.

Features

  • Append-only Partitioned Log: The core storage mechanism.
  • Segment-Based Storage: Logs are broken into segments with sparse .index files for fast, efficient reads.
  • Pluggable Storage: Supports SingleLogStorage (one file) or SegmentedLogStorage (retention-ready).
  • Controller Cluster: A controller-based architecture (no "single mode") manages cluster state.
  • Metadata & Liveness: The Controller tracks broker liveness (via heartbeats) and partition assignments.
  • Leader Election: The Controller automatically elects new leaders when brokers fail
  • Producer/Consumer APIs: Asynchronous clients for producing and consuming data.
  • Log Retention: Supports per-topic log retention by time (retention_ms) or size (retention_bytes)
  • HTTP Admin Dashboard: A built-in, lightweight web UI (via FastAPI) to view cluster status.

Configuration Management

TinyStream uses a 4-layer "override" system for configuration, managed by the ConfigManager.

The final value for any setting is chosen in this order of priority:

  • CLI Arguments: (e.g., --controller-uri)
  • Environment Variables: (e.g., TINYSTREAM_CONTROLLER_URI)
  • User-Provided Config File: (e.g., --config test_confs/broker-1.ini)
  • Default Component Config File: (e.g., tinystream/config/controller.ini)

This allows you to have a set of default configs and override them at runtime. For example, you can start a broker and tell it where the controller is via an environment variable, rather than modifying its config file.

Installation

The project uses uv for dependency management and execution.

  1. Clone the repository:
    git clone [https://github.com/Olamyy/tinystream](https://github.com/Olamyy/tinystream)
    cd tinystream
  2. Install the required dependencies:
    uv install

Quick Start: Running Locally

Here is how to run a minimal "cluster" (one controller, one broker) on your machine.

Step 1: Start the Controller

The Controller manages cluster metadata (topics, brokers, partition leaders).

uv run python -m tinystream.controller

The controller will start:

  • Its RPC Server on localhost:9093 (for Brokers to connect).
  • The Metastore API / Dashboard on http://localhost:3200.

Step 2: Start a Broker

The Broker stores data. This command will load tinystream/config/broker.ini (which knows the controller's address) and start the broker with ID 1.

uv run python -m tinystream.broker --broker-id 1

The broker will start:

  • Its RPC Server on localhost:9095 (from broker.ini, for clients).
  • It will then connect to the Controller at localhost:9093 to register itself.

Step 4: Create a Topic

Use the admin client to tell the Controller to create a new topic.

uv run python -m tinystream.admin create-topic \
--topic "events" \
--partitions 3 \
--replication-factor 1 \
--metastore "localhost:6000"

Step 5: Produce Messages

importasyncioimportargparsefromtinystream.client.producerimportProducerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
producer=Producer(config=config)
try:
awaitproducer.connect()
print("Producer connected. Sending 10 messages...")
foriinrange(10):
msg=f"hello-tinystream-{i}"key=f"user-{i%2}"print(f"Sending: {msg} (key: {key})")
response=awaitproducer.send("events", msg.encode('utf-8'), key=key)
print(f"-> Broker response: {response}")
awaitasyncio.sleep(0.5)
exceptExceptionase:
print(f"Error: {e}")
finally:
awaitproducer.close()
if__name__=="__main__":
asyncio.run(run())

Step 6: Consume Messages

importasyncioimportargparsefromtinystream.client.consumerimportConsumerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
consumer=Consumer(config=config, group_id="my-test-group")
try:
awaitconsumer.connect()
print("Consumer connected.")
consumer.assign(topic="events", partition=0, start_offset=0)
print("Consuming from 'events-0'. Press Ctrl+C to stop.")
whileTrue:
messages=awaitconsumer.poll(max_messages=5)
ifmessages:
formsginmessages:
print(f"Received: {msg.decode('utf-8')}")
awaitconsumer.commit()
awaitasyncio.sleep(1)
exceptKeyboardInterrupt:
print("\nStopping consumer...")
finally:
awaitconsumer.close()
if__name__=="__main__":
asyncio.run(run())

Load Testing

A load test script is included in load_test.py. It uses spawns worker tasks to send data in parallel.

Before running, ensure the topic exists:

uv run python -m tinystream.admin create-topic --topic "load_test" --partitions 3 --replication-factor 1

To run the test for 60 seconds with 50 concurrent workers:

uv run python load_test.py \
--topic "load_test" \
--num-workers 50 \
--message-size 1024 \
--run-time 60

Load Test Results

TODO: Add results from a benchmark run (e.g., on an M4 Mac with 36GB memory) here.

Running Components in Isolation

For quick testing, each core component can be run in isolation directly as a module:

  • Controller: uv run python -m tinystream.controller
  • Broker: uv run python -m tinystream.broker
  • Producer: uv run python -m tinystream.client.producer
  • Consumer: uv run python -m tinystream.client.consumer
  • Admin: uv run python -m tinystream.client.admin

Architecture Overview

TinyStream is split into five layers:

┌────────────────────────────────────────────┐
│ Producers / Consumers │
│ • Send and fetch records from topics │
│ • Commit offsets │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Broker │
│ • Accepts produce/fetch requests │
│ • Manages topic partitions │
│ • Serves leader/follower replicas │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Partition │
│ • Manages append-only log segments |
│ • Handles retention and compaction │
│ • Stores offset and time indexes │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Segment │
│ • File-based, append-only structure │
│ • Supports batch reads via index lookups │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Storage │
│ • Local disk or tiered storage backend │
│ • Retention + compaction policy engine │
└────────────────────────────────────────────┘

Each topic is split into partitions, and each partition is an append-only log. Brokers host one or more partitions; producers and consumers talk to brokers via lightweight RPC.

Partition Storage Layout

Each partition is stored on disk as a directory containing segment and index files:

data/
└── topics/
└── user_clicks/
└── partition-0/
├── 00000000000000000000.log
├── 00000000000000000000.index
├── 00000000000001000000.log
├── 00000000000001000000.index
├── partition.metadata
└── lock

Messages are never deleted after consumption — instead, TinyStream enforces a retention policy (by time or size) to delete or compact old segments.

What to Test

CategoryExample
ReplicationWrite to leader → restart follower → verify catch-up
Leader ElectionKill leader → ensure controller reassigns
RetentionConfigure short TTL → check old segment deletion
ConsistencyCompare offsets after recovery
Consumer GroupsAdd/remove consumers → verify rebalancing

About

A lightweight streaming engine.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TinyStream

TinyStream is a lightweight streaming engine in Python, inspired by Apache Kafka.

Features

  • Append-only Partitioned Log: The core storage mechanism.
  • Segment-Based Storage: Logs are broken into segments with sparse .index files for fast, efficient reads.
  • Pluggable Storage: Supports SingleLogStorage (one file) or SegmentedLogStorage (retention-ready).
  • Controller Cluster: A controller-based architecture (no "single mode") manages cluster state.
  • Metadata & Liveness: The Controller tracks broker liveness (via heartbeats) and partition assignments.
  • Leader Election: The Controller automatically elects new leaders when brokers fail
  • Producer/Consumer APIs: Asynchronous clients for producing and consuming data.
  • Log Retention: Supports per-topic log retention by time (retention_ms) or size (retention_bytes)
  • HTTP Admin Dashboard: A built-in, lightweight web UI (via FastAPI) to view cluster status.

Configuration Management

TinyStream uses a 4-layer "override" system for configuration, managed by the ConfigManager.

The final value for any setting is chosen in this order of priority:

  • CLI Arguments: (e.g., --controller-uri)
  • Environment Variables: (e.g., TINYSTREAM_CONTROLLER_URI)
  • User-Provided Config File: (e.g., --config test_confs/broker-1.ini)
  • Default Component Config File: (e.g., tinystream/config/controller.ini)

This allows you to have a set of default configs and override them at runtime. For example, you can start a broker and tell it where the controller is via an environment variable, rather than modifying its config file.

Installation

The project uses uv for dependency management and execution.

  1. Clone the repository:
    git clone [https://github.com/Olamyy/tinystream](https://github.com/Olamyy/tinystream)
    cd tinystream
  2. Install the required dependencies:
    uv install

Quick Start: Running Locally

Here is how to run a minimal "cluster" (one controller, one broker) on your machine.

Step 1: Start the Controller

The Controller manages cluster metadata (topics, brokers, partition leaders).

uv run python -m tinystream.controller

The controller will start:

  • Its RPC Server on localhost:9093 (for Brokers to connect).
  • The Metastore API / Dashboard on http://localhost:3200.

Step 2: Start a Broker

The Broker stores data. This command will load tinystream/config/broker.ini (which knows the controller's address) and start the broker with ID 1.

uv run python -m tinystream.broker --broker-id 1

The broker will start:

  • Its RPC Server on localhost:9095 (from broker.ini, for clients).
  • It will then connect to the Controller at localhost:9093 to register itself.

Step 4: Create a Topic

Use the admin client to tell the Controller to create a new topic.

uv run python -m tinystream.admin create-topic \
--topic "events" \
--partitions 3 \
--replication-factor 1 \
--metastore "localhost:6000"

Step 5: Produce Messages

importasyncioimportargparsefromtinystream.client.producerimportProducerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
producer=Producer(config=config)
try:
awaitproducer.connect()
print("Producer connected. Sending 10 messages...")
foriinrange(10):
msg=f"hello-tinystream-{i}"key=f"user-{i%2}"print(f"Sending: {msg} (key: {key})")
response=awaitproducer.send("events", msg.encode('utf-8'), key=key)
print(f"-> Broker response: {response}")
awaitasyncio.sleep(0.5)
exceptExceptionase:
print(f"Error: {e}")
finally:
awaitproducer.close()
if__name__=="__main__":
asyncio.run(run())

Step 6: Consume Messages

importasyncioimportargparsefromtinystream.client.consumerimportConsumerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
consumer=Consumer(config=config, group_id="my-test-group")
try:
awaitconsumer.connect()
print("Consumer connected.")
consumer.assign(topic="events", partition=0, start_offset=0)
print("Consuming from 'events-0'. Press Ctrl+C to stop.")
whileTrue:
messages=awaitconsumer.poll(max_messages=5)
ifmessages:
formsginmessages:
print(f"Received: {msg.decode('utf-8')}")
awaitconsumer.commit()
awaitasyncio.sleep(1)
exceptKeyboardInterrupt:
print("\nStopping consumer...")
finally:
awaitconsumer.close()
if__name__=="__main__":
asyncio.run(run())

Load Testing

A load test script is included in load_test.py. It uses spawns worker tasks to send data in parallel.

Before running, ensure the topic exists:

uv run python -m tinystream.admin create-topic --topic "load_test" --partitions 3 --replication-factor 1

To run the test for 60 seconds with 50 concurrent workers:

uv run python load_test.py \
--topic "load_test" \
--num-workers 50 \
--message-size 1024 \
--run-time 60

Load Test Results

TODO: Add results from a benchmark run (e.g., on an M4 Mac with 36GB memory) here.

Running Components in Isolation

For quick testing, each core component can be run in isolation directly as a module:

  • Controller: uv run python -m tinystream.controller
  • Broker: uv run python -m tinystream.broker
  • Producer: uv run python -m tinystream.client.producer
  • Consumer: uv run python -m tinystream.client.consumer
  • Admin: uv run python -m tinystream.client.admin

Architecture Overview

TinyStream is split into five layers:

┌────────────────────────────────────────────┐
│ Producers / Consumers │
│ • Send and fetch records from topics │
│ • Commit offsets │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Broker │
│ • Accepts produce/fetch requests │
│ • Manages topic partitions │
│ • Serves leader/follower replicas │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Partition │
│ • Manages append-only log segments |
│ • Handles retention and compaction │
│ • Stores offset and time indexes │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Segment │
│ • File-based, append-only structure │
│ • Supports batch reads via index lookups │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Storage │
│ • Local disk or tiered storage backend │
│ • Retention + compaction policy engine │
└────────────────────────────────────────────┘

Each topic is split into partitions, and each partition is an append-only log. Brokers host one or more partitions; producers and consumers talk to brokers via lightweight RPC.

Partition Storage Layout

Each partition is stored on disk as a directory containing segment and index files:

data/
└── topics/
└── user_clicks/
└── partition-0/
├── 00000000000000000000.log
├── 00000000000000000000.index
├── 00000000000001000000.log
├── 00000000000001000000.index
├── partition.metadata
└── lock

Messages are never deleted after consumption — instead, TinyStream enforces a retention policy (by time or size) to delete or compact old segments.

What to Test

CategoryExample
ReplicationWrite to leader → restart follower → verify catch-up
Leader ElectionKill leader → ensure controller reassigns
RetentionConfigure short TTL → check old segment deletion
ConsistencyCompare offsets after recovery
Consumer GroupsAdd/remove consumers → verify rebalancing

About

A lightweight streaming engine.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

TinyStream

TinyStream is a lightweight streaming engine in Python, inspired by Apache Kafka.

Features

  • Append-only Partitioned Log: The core storage mechanism.
  • Segment-Based Storage: Logs are broken into segments with sparse .index files for fast, efficient reads.
  • Pluggable Storage: Supports SingleLogStorage (one file) or SegmentedLogStorage (retention-ready).
  • Controller Cluster: A controller-based architecture (no "single mode") manages cluster state.
  • Metadata & Liveness: The Controller tracks broker liveness (via heartbeats) and partition assignments.
  • Leader Election: The Controller automatically elects new leaders when brokers fail
  • Producer/Consumer APIs: Asynchronous clients for producing and consuming data.
  • Log Retention: Supports per-topic log retention by time (retention_ms) or size (retention_bytes)
  • HTTP Admin Dashboard: A built-in, lightweight web UI (via FastAPI) to view cluster status.

Configuration Management

TinyStream uses a 4-layer "override" system for configuration, managed by the ConfigManager.

The final value for any setting is chosen in this order of priority:

  • CLI Arguments: (e.g., --controller-uri)
  • Environment Variables: (e.g., TINYSTREAM_CONTROLLER_URI)
  • User-Provided Config File: (e.g., --config test_confs/broker-1.ini)
  • Default Component Config File: (e.g., tinystream/config/controller.ini)

This allows you to have a set of default configs and override them at runtime. For example, you can start a broker and tell it where the controller is via an environment variable, rather than modifying its config file.

Installation

The project uses uv for dependency management and execution.

  1. Clone the repository:
    git clone [https://github.com/Olamyy/tinystream](https://github.com/Olamyy/tinystream)
    cd tinystream
  2. Install the required dependencies:
    uv install

Quick Start: Running Locally

Here is how to run a minimal "cluster" (one controller, one broker) on your machine.

Step 1: Start the Controller

The Controller manages cluster metadata (topics, brokers, partition leaders).

uv run python -m tinystream.controller

The controller will start:

  • Its RPC Server on localhost:9093 (for Brokers to connect).
  • The Metastore API / Dashboard on http://localhost:3200.

Step 2: Start a Broker

The Broker stores data. This command will load tinystream/config/broker.ini (which knows the controller's address) and start the broker with ID 1.

uv run python -m tinystream.broker --broker-id 1

The broker will start:

  • Its RPC Server on localhost:9095 (from broker.ini, for clients).
  • It will then connect to the Controller at localhost:9093 to register itself.

Step 4: Create a Topic

Use the admin client to tell the Controller to create a new topic.

uv run python -m tinystream.admin create-topic \
--topic "events" \
--partitions 3 \
--replication-factor 1 \
--metastore "localhost:6000"

Step 5: Produce Messages

importasyncioimportargparsefromtinystream.client.producerimportProducerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
producer=Producer(config=config)
try:
awaitproducer.connect()
print("Producer connected. Sending 10 messages...")
foriinrange(10):
msg=f"hello-tinystream-{i}"key=f"user-{i%2}"print(f"Sending: {msg} (key: {key})")
response=awaitproducer.send("events", msg.encode('utf-8'), key=key)
print(f"-> Broker response: {response}")
awaitasyncio.sleep(0.5)
exceptExceptionase:
print(f"Error: {e}")
finally:
awaitproducer.close()
if__name__=="__main__":
asyncio.run(run())

Step 6: Consume Messages

importasyncioimportargparsefromtinystream.client.consumerimportConsumerfromtinystream.config.managerimportConfigManagerasyncdefrun():
args=argparse.Namespace(config=None, controller_uri=None, metastore_uri=None)
config=ConfigManager(args, component_type="broker")
consumer=Consumer(config=config, group_id="my-test-group")
try:
awaitconsumer.connect()
print("Consumer connected.")
consumer.assign(topic="events", partition=0, start_offset=0)
print("Consuming from 'events-0'. Press Ctrl+C to stop.")
whileTrue:
messages=awaitconsumer.poll(max_messages=5)
ifmessages:
formsginmessages:
print(f"Received: {msg.decode('utf-8')}")
awaitconsumer.commit()
awaitasyncio.sleep(1)
exceptKeyboardInterrupt:
print("\nStopping consumer...")
finally:
awaitconsumer.close()
if__name__=="__main__":
asyncio.run(run())

Load Testing

A load test script is included in load_test.py. It uses spawns worker tasks to send data in parallel.

Before running, ensure the topic exists:

uv run python -m tinystream.admin create-topic --topic "load_test" --partitions 3 --replication-factor 1

To run the test for 60 seconds with 50 concurrent workers:

uv run python load_test.py \
--topic "load_test" \
--num-workers 50 \
--message-size 1024 \
--run-time 60

Load Test Results

TODO: Add results from a benchmark run (e.g., on an M4 Mac with 36GB memory) here.

Running Components in Isolation

For quick testing, each core component can be run in isolation directly as a module:

  • Controller: uv run python -m tinystream.controller
  • Broker: uv run python -m tinystream.broker
  • Producer: uv run python -m tinystream.client.producer
  • Consumer: uv run python -m tinystream.client.consumer
  • Admin: uv run python -m tinystream.client.admin

Architecture Overview

TinyStream is split into five layers:

┌────────────────────────────────────────────┐
│ Producers / Consumers │
│ • Send and fetch records from topics │
│ • Commit offsets │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Broker │
│ • Accepts produce/fetch requests │
│ • Manages topic partitions │
│ • Serves leader/follower replicas │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Partition │
│ • Manages append-only log segments |
│ • Handles retention and compaction │
│ • Stores offset and time indexes │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Segment │
│ • File-based, append-only structure │
│ • Supports batch reads via index lookups │
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Storage │
│ • Local disk or tiered storage backend │
│ • Retention + compaction policy engine │
└────────────────────────────────────────────┘

Each topic is split into partitions, and each partition is an append-only log. Brokers host one or more partitions; producers and consumers talk to brokers via lightweight RPC.

Partition Storage Layout

Each partition is stored on disk as a directory containing segment and index files:

data/
└── topics/
└── user_clicks/
└── partition-0/
├── 00000000000000000000.log
├── 00000000000000000000.index
├── 00000000000001000000.log
├── 00000000000001000000.index
├── partition.metadata
└── lock

Messages are never deleted after consumption — instead, TinyStream enforces a retention policy (by time or size) to delete or compact old segments.

What to Test

CategoryExample
ReplicationWrite to leader → restart follower → verify catch-up
Leader ElectionKill leader → ensure controller reassigns
RetentionConfigure short TTL → check old segment deletion
ConsistencyCompare offsets after recovery
Consumer GroupsAdd/remove consumers → verify rebalancing

About

A lightweight streaming engine.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages