You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by gk...@apache.org on 2025/08/18 11:26:18 UTC

(iggy) 01/02: cg init

This is an automated email from the ASF dual-hosted git repository.

gkoszyk pushed a commit to branch remove_old_api
in repository https://gitbox.apache.org/repos/asf/iggy.git

commit de3ed5b48f38d2b0f28df9dc9853a6c09d4a45c6
Author: numminex <g....@gmail.com>
AuthorDate: Mon Aug 18 10:53:04 2025 +0200

    cg init
---
 .../create_consumer_group_handler.rs               |  43 --
 .../partitions/create_partitions_handler.rs        |  66 +--
 .../partitions/delete_partitions_handler.rs        |  53 +--
 .../handlers/streams/create_stream_handler.rs      |   2 +-
 .../handlers/streams/delete_stream_handler.rs      |  51 +--
 .../binary/handlers/streams/get_stream_handler.rs  |   5 +-
 .../binary/handlers/streams/get_streams_handler.rs |   2 +-
 .../handlers/streams/purge_stream_handler.rs       |  13 -
 .../handlers/streams/update_stream_handler.rs      |  13 -
 .../binary/handlers/topics/create_topic_handler.rs |  11 +-
 .../binary/handlers/topics/delete_topic_handler.rs |   3 +-
 .../binary/handlers/topics/get_topic_handler.rs    |  16 +-
 .../binary/handlers/topics/get_topics_handler.rs   |  16 +-
 .../binary/handlers/topics/purge_topic_handler.rs  |   2 +-
 .../binary/handlers/topics/update_topic_handler.rs |  23 +-
 core/server/src/binary/mapper.rs                   |   3 +-
 core/server/src/shard/mod.rs                       |  42 +-
 core/server/src/shard/system/consumer_groups.rs    | 460 ++++-----------------
 core/server/src/shard/system/consumer_offsets.rs   |   9 +
 core/server/src/shard/system/messages.rs           |  24 +-
 core/server/src/shard/system/partitions.rs         | 219 ++--------
 core/server/src/shard/system/segments.rs           |  92 +----
 core/server/src/shard/system/streams.rs            |  26 +-
 core/server/src/shard/system/topics.rs             |  31 +-
 core/server/src/shard/system/utils.rs              |  21 +-
 core/server/src/slab/consumer_groups.rs            | 148 ++++++-
 core/server/src/slab/helpers.rs                    |  35 +-
 core/server/src/slab/partitions.rs                 |   4 +-
 core/server/src/slab/streams.rs                    | 108 ++++-
 core/server/src/slab/topics.rs                     | 104 ++++-
 core/server/src/slab/traits_ext.rs                 |   3 +
 core/server/src/streaming/partitions/helpers.rs    |  18 +
 core/server/src/streaming/partitions/mod.rs        |   1 +
 .../server/src/streaming/topics/consumer_group2.rs | 265 +++++++-----
 core/server/src/streaming/topics/helpers.rs        | 241 ++++++++++-
 core/server/src/streaming/topics/topic2.rs         |  20 +-
 36 files changed, 983 insertions(+), 1210 deletions(-)

diff --git a/core/server/src/binary/handlers/consumer_groups/create_consumer_group_handler.rs b/core/server/src/binary/handlers/consumer_groups/create_consumer_group_handler.rs
index 898a8ad2..a941ee5c 100644
--- a/core/server/src/binary/handlers/consumer_groups/create_consumer_group_handler.rs
+++ b/core/server/src/binary/handlers/consumer_groups/create_consumer_group_handler.rs
@@ -48,7 +48,6 @@ impl ServerCommandHandler for CreateConsumerGroup {
         shard: &Rc<IggyShard>,
     ) -> Result<(), IggyError> {
         debug!("session: {session}, command: {self}");
-        let members = ArcShift::new(slab::Slab::with_capacity(MEMBERS_CAPACITY));
         let cg_id = shard.create_consumer_group2(
             session,
             &self.stream_id,
@@ -66,48 +65,6 @@ impl ServerCommandHandler for CreateConsumerGroup {
         };
         let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
 
-        let consumer_group_id = shard
-                .create_consumer_group(
-                    session,
-                    &self.stream_id,
-                    &self.topic_id,
-                    self.group_id,
-                    &self.name,
-                )
-                .with_error_context(|error| {
-                    format!(
-                        "{COMPONENT} (error: {error}) - failed to create consumer group for stream_id: {}, topic_id: {}, group_id: {:?}, session: {session}",
-                        self.stream_id, self.topic_id, self.group_id
-                    )
-                })?;
-        let event = ShardEvent::CreatedConsumerGroup {
-            stream_id: self.stream_id.clone(),
-            topic_id: self.topic_id.clone(),
-            consumer_group_id: self.group_id,
-            name: self.name.clone(),
-        };
-        let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-
-        let stream = shard.find_stream(session, &self.stream_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to find stream with ID: {} for session: {}",
-                    self.stream_id, session
-                )
-            })?;
-        let consumer_group = shard.get_consumer_group(session, &stream, &self.topic_id, &consumer_group_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to get consumer group for stream_id: {}, topic_id: {}, group_id: {:?}, session: {session}",
-                    self.stream_id, self.topic_id, consumer_group_id
-                )
-            })?.unwrap();
-        let group_id = consumer_group.group_id;
-        let response = mapper::map_consumer_group(&consumer_group);
-
-        let stream_id = self.stream_id.clone();
-        let topic_id = self.topic_id.clone();
-
         shard
             .state
         .apply(
diff --git a/core/server/src/binary/handlers/partitions/create_partitions_handler.rs b/core/server/src/binary/handlers/partitions/create_partitions_handler.rs
index 50442373..7f18318a 100644
--- a/core/server/src/binary/handlers/partitions/create_partitions_handler.rs
+++ b/core/server/src/binary/handlers/partitions/create_partitions_handler.rs
@@ -23,11 +23,11 @@ use crate::shard::IggyShard;
 use crate::shard::transmission::event::ShardEvent;
 use crate::state::command::EntryCommand;
 use crate::streaming::session::Session;
+use crate::streaming::{streams, topics};
 use anyhow::Result;
 use error_set::ErrContext;
 use iggy_common::IggyError;
 use iggy_common::create_partitions::CreatePartitions;
-use iggy_common::locking::IggyRwLockFn;
 use std::rc::Rc;
 use tracing::{debug, instrument};
 
@@ -59,62 +59,16 @@ impl ServerCommandHandler for CreatePartitions {
             partitions,
         };
         let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
+        //TODO: Create shard table records.
 
-        let partition_ids = shard
-            .create_partitions(
-                session,
-                &self.stream_id,
-                &self.topic_id,
-                self.partitions_count,
-            )
-            .await
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to create partitions for stream_id: {}, topic_id: {}, session: {}",
-                    self.stream_id, self.topic_id, session
-                )
-            })?;
-        let stream_id = self.stream_id.clone();
-        let topic_id = self.topic_id.clone();
-        let event = ShardEvent::CreatedPartitions {
-            stream_id: self.stream_id.clone(),
-            topic_id: self.topic_id.clone(),
-            partitions_count: partition_ids.len() as u32,
-        };
-        let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-
-        let stream = shard.get_stream(&stream_id).unwrap();
-        let topic = stream.get_topic(&topic_id).unwrap();
-        let numeric_stream_id = stream.stream_id;
-        let numeric_topic_id = topic.topic_id;
-
-        let records = shard
-            .create_shard_table_records(&partition_ids, numeric_stream_id, numeric_topic_id)
-            .collect::<Vec<_>>();
-
-        // Open partition and segments for that particular shard.
-        for (ns, shard_info) in records.iter() {
-            let partition = topic.get_partition(ns.partition_id).unwrap();
-            let mut partition = partition.write().await;
-            partition.persist().await.unwrap();
-            if shard_info.id() == shard.id {
-                let partition_id = ns.partition_id;
-                partition.open().await.with_error_context(|error| {
-                    format!(
-                        "{COMPONENT} (error: {error}) - failed to open partition with ID: {partition_id} in topic with ID: {topic_id} for stream with ID: {stream_id}"
-                    )
-                })?;
-            }
-        }
-        shard.insert_shard_table_records(records);
-        // Broadcast the event to all shards.
-        let event = ShardEvent::CreatedShardTableRecords {
-            stream_id: numeric_stream_id,
-            topic_id: numeric_topic_id,
-            partition_ids,
-        };
-        let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-
+        let stream_id = shard
+            .streams2
+            .with_stream_by_id(&self.stream_id, streams::helpers::get_stream_id());
+        let topic_id = shard.streams2.with_topic_by_id(
+            &self.stream_id,
+            &self.topic_id,
+            topics::helpers::get_topic_id(),
+        );
         shard
         .state
         .apply(
diff --git a/core/server/src/binary/handlers/partitions/delete_partitions_handler.rs b/core/server/src/binary/handlers/partitions/delete_partitions_handler.rs
index 5db7ed54..ab248b17 100644
--- a/core/server/src/binary/handlers/partitions/delete_partitions_handler.rs
+++ b/core/server/src/binary/handlers/partitions/delete_partitions_handler.rs
@@ -64,58 +64,7 @@ impl ServerCommandHandler for DeletePartitions {
             partition_ids: deleted_partition_ids2,
         };
         let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-
-        let partition_ids = shard
-            .delete_partitions(
-                session,
-                &self.stream_id,
-                &self.topic_id,
-                self.partitions_count,
-            )
-            .await
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to delete partitions for topic with ID: {topic_id} in stream with ID: {stream_id}, session: {session}",
-                )
-            })?;
-        let event = ShardEvent::DeletedPartitions {
-            stream_id: stream_id.clone(),
-            topic_id: topic_id.clone(),
-            partition_ids: partition_ids.clone(),
-        };
-        let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-        let stream = shard.get_stream(&stream_id).with_error_context(|error| {
-            format!("{COMPONENT} (error: {error}) - failed to get stream with ID: {stream_id}")
-        })?;
-        let topic = stream
-            .get_topic(&topic_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to get topic with ID: {topic_id} in stream with ID: {stream_id}"
-                )
-            })?;
-        let numeric_stream_id = stream.stream_id;
-        let numeric_topic_id = topic.topic_id;
-        let namespaces = partition_ids
-            .into_iter()
-            .map(|id| IggyNamespace::new(numeric_stream_id, numeric_topic_id, id))
-            .collect::<Vec<_>>();
-        let records = shard.remove_shard_table_records(&namespaces);
-        for (ns, shard_info) in records.iter() {
-            if shard_info.id() == shard.id {
-                let partition = topic.get_partition(ns.partition_id)?;
-                let mut partition = partition.write().await;
-                partition.delete().await.with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to delete partition with ID: {} in topic with ID: {}",
-                    ns.partition_id,
-                    numeric_topic_id
-                )
-            })?;
-            }
-        }
-        let event = ShardEvent::DeletedShardTableRecords { namespaces };
-        let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
+        // TODO: Delete shard table records.
 
         shard
         .state
diff --git a/core/server/src/binary/handlers/streams/create_stream_handler.rs b/core/server/src/binary/handlers/streams/create_stream_handler.rs
index 4da9950e..2cab0ab2 100644
--- a/core/server/src/binary/handlers/streams/create_stream_handler.rs
+++ b/core/server/src/binary/handlers/streams/create_stream_handler.rs
@@ -67,7 +67,7 @@ impl ServerCommandHandler for CreateStream {
 
         let response = shard
             .streams2
-            .with_by_id(created_stream_id, |(root, stats)| {
+            .with_components_by_id(created_stream_id, |(root, stats)| {
                 mapper::map_stream(&root, &stats)
             });
         shard
diff --git a/core/server/src/binary/handlers/streams/delete_stream_handler.rs b/core/server/src/binary/handlers/streams/delete_stream_handler.rs
index c7b9ad2c..8b524dba 100644
--- a/core/server/src/binary/handlers/streams/delete_stream_handler.rs
+++ b/core/server/src/binary/handlers/streams/delete_stream_handler.rs
@@ -67,53 +67,10 @@ impl ServerCommandHandler for DeleteStream {
             id: stream2.id(),
             stream_id: self.stream_id.clone(),
         };
-        let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-
-        let stream = shard
-                .delete_stream(session, &self.stream_id)
-                .with_error_context(|error| {
-                    format!("{COMPONENT} (error: {error}) - failed to delete stream with ID: {stream_id}, session: {session}")
-                })?;
-        shard_info!(
-            shard.id,
-            "Deleted stream with name: {}, ID: {}",
-            stream.name,
-            stream.stream_id
-        );
-        // First we have to go over all of the partitions inside of topics
-        // and make sure that they are deleted.
-        for topic in stream.get_topics() {
-            let partitions = topic.get_partitions();
-            let mut namespaces = Vec::new();
-            for partition in partitions {
-                let partition_id = partition.read().await.partition_id;
-                let namespace = IggyNamespace::new(stream.stream_id, topic.topic_id, partition_id);
-                namespaces.push(namespace);
-            }
-            let records = shard.remove_shard_table_records(&namespaces);
-            for (ns, shard_info) in records {
-                if shard_info.id() == shard.id {
-                    let partition = topic.get_partition(ns.partition_id).unwrap();
-                    let mut partition = partition.write().await;
-                    let partition_id = partition.partition_id;
-                    partition.delete().await.with_error_context(|error| {
-                        format!("{COMPONENT} (error: {error}) - failed to delete partition in stream: {self}, partition: {partition_id}")
-                    })?;
-                }
-            }
-            let event = ShardEvent::DeletedShardTableRecords { namespaces };
-            let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-            topic.delete().await.with_error_context(|error| {
-                format!("{COMPONENT} (error: {error}) - failed to delete topic in stream: {self}")
-            })?;
-        }
-        if stream.delete().await.is_err() {
-            return Err(IggyError::CannotDeleteStream(stream.stream_id));
-        }
-        let event = ShardEvent::DeletedStream {
-            stream_id: self.stream_id.clone(),
-        };
-        let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
+        let _responses = shard.broadcast_event_to_all_shards(event).await;
+        // Drop the stream to force readers/writers to be dropped.
+        drop(stream2);
+        // TODO: Remove all the directories and files related to the stream.
 
         shard
             .state
diff --git a/core/server/src/binary/handlers/streams/get_stream_handler.rs b/core/server/src/binary/handlers/streams/get_stream_handler.rs
index 15a9500f..dfd4cc4a 100644
--- a/core/server/src/binary/handlers/streams/get_stream_handler.rs
+++ b/core/server/src/binary/handlers/streams/get_stream_handler.rs
@@ -23,6 +23,7 @@ use crate::binary::sender::SenderKind;
 use crate::shard::IggyShard;
 use crate::slab::traits_ext::EntityComponentSystem;
 use crate::streaming::session::Session;
+use crate::streaming::streams;
 use anyhow::Result;
 use error_set::ErrContext;
 use iggy_common::IggyError;
@@ -47,7 +48,7 @@ impl ServerCommandHandler for GetStream {
         shard.ensure_stream_exists(&self.stream_id)?;
         let stream_id = shard
             .streams2
-            .with_root_by_id(&self.stream_id, |root| root.id());
+            .with_stream_by_id(&self.stream_id, streams::helpers::get_stream_id());
         shard
             .permissioner
             .borrow()
@@ -61,7 +62,7 @@ impl ServerCommandHandler for GetStream {
             });
         let response = shard
             .streams2
-            .with_by_id(stream_id, |(root, stats)| mapper::map_stream(&root, &stats));
+            .with_components_by_id(stream_id, |(root, stats)| mapper::map_stream(&root, &stats));
         sender.send_ok_response(&response).await?;
         Ok(())
     }
diff --git a/core/server/src/binary/handlers/streams/get_streams_handler.rs b/core/server/src/binary/handlers/streams/get_streams_handler.rs
index 9010a383..7046e3c1 100644
--- a/core/server/src/binary/handlers/streams/get_streams_handler.rs
+++ b/core/server/src/binary/handlers/streams/get_streams_handler.rs
@@ -56,7 +56,7 @@ impl ServerCommandHandler for GetStreams {
                 )
             })?;
 
-        let response = shard.streams2.with(|stream_ref| {
+        let response = shard.streams2.with_components(|stream_ref| {
             let (roots, stats) = stream_ref.into_components();
             mapper::map_streams(&roots, &stats)
         });
diff --git a/core/server/src/binary/handlers/streams/purge_stream_handler.rs b/core/server/src/binary/handlers/streams/purge_stream_handler.rs
index 1d242023..39e32a12 100644
--- a/core/server/src/binary/handlers/streams/purge_stream_handler.rs
+++ b/core/server/src/binary/handlers/streams/purge_stream_handler.rs
@@ -55,19 +55,6 @@ impl ServerCommandHandler for PurgeStream {
             stream_id: self.stream_id.clone(),
         };
         let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-
-        shard
-            .purge_stream(session, &self.stream_id)
-            .await
-            .with_error_context(|error| {
-                format!("{COMPONENT} (error: {error}) - failed to purge stream with id: {stream_id}, session: {session}")
-            })?;
-
-        let event = ShardEvent::PurgedStream {
-            stream_id: self.stream_id.clone(),
-        };
-        let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-
         shard
             .state
             .apply(session.get_user_id(), &EntryCommand::PurgeStream(self))
diff --git a/core/server/src/binary/handlers/streams/update_stream_handler.rs b/core/server/src/binary/handlers/streams/update_stream_handler.rs
index f8ca41ab..ebfe1121 100644
--- a/core/server/src/binary/handlers/streams/update_stream_handler.rs
+++ b/core/server/src/binary/handlers/streams/update_stream_handler.rs
@@ -57,19 +57,6 @@ impl ServerCommandHandler for UpdateStream {
             name: self.name.clone(),
         };
         let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-
-        shard
-                .update_stream(session, &self.stream_id, &self.name)
-                .await
-                .with_error_context(|error| {
-                    format!("{COMPONENT} (error: {error}) - failed to update stream with id: {stream_id}, session: {session}")
-                })?;
-        let event = ShardEvent::UpdatedStream {
-            stream_id: self.stream_id.clone(),
-            name: self.name.clone(),
-        };
-        let _responses = shard.broadcast_event_to_all_shards(event.into()).await;
-
         shard
             .state
             .apply(session.get_user_id(), &EntryCommand::UpdateStream(self))
diff --git a/core/server/src/binary/handlers/topics/create_topic_handler.rs b/core/server/src/binary/handlers/topics/create_topic_handler.rs
index 223ba118..7984d3b4 100644
--- a/core/server/src/binary/handlers/topics/create_topic_handler.rs
+++ b/core/server/src/binary/handlers/topics/create_topic_handler.rs
@@ -26,6 +26,7 @@ use crate::slab::traits_ext::EntityMarker;
 use crate::state::command::EntryCommand;
 use crate::state::models::CreateTopicWithId;
 use crate::streaming::session::Session;
+use crate::streaming::streams;
 use anyhow::Result;
 use error_set::ErrContext;
 use iggy_common::create_topic::CreateTopic;
@@ -63,7 +64,7 @@ impl ServerCommandHandler for CreateTopic {
 
         let stream_id = shard
             .streams2
-            .with_root_by_id(&self.stream_id, |root| root.id());
+            .with_stream_by_id(&self.stream_id, streams::helpers::get_stream_id());
         let topic_id = topic.id();
         // Send events for topic creation.
         let event = ShardEvent::CreatedTopic2 {
@@ -72,7 +73,7 @@ impl ServerCommandHandler for CreateTopic {
         };
         let _responses = shard.broadcast_event_to_all_shards(event).await;
 
-        shard
+        let partitions = shard
             .create_partitions2(
                 session,
                 &self.stream_id,
@@ -80,6 +81,12 @@ impl ServerCommandHandler for CreateTopic {
                 self.partitions_count,
             )
             .await?;
+        let event = ShardEvent::CreatedPartitions2 {
+            stream_id: self.stream_id.clone(),
+            topic_id: Identifier::numeric(topic_id as u32).unwrap(),
+            partitions,
+        };
+        let _responses = shard.broadcast_event_to_all_shards(event).await;
         // TODO: Create shard_table records for partitions.
         let response = shard.streams2.with_topic_by_id(
             &self.stream_id,
diff --git a/core/server/src/binary/handlers/topics/delete_topic_handler.rs b/core/server/src/binary/handlers/topics/delete_topic_handler.rs
index bc7f4560..1cfec58d 100644
--- a/core/server/src/binary/handlers/topics/delete_topic_handler.rs
+++ b/core/server/src/binary/handlers/topics/delete_topic_handler.rs
@@ -24,6 +24,7 @@ use crate::shard::transmission::event::ShardEvent;
 use crate::shard_info;
 use crate::state::command::EntryCommand;
 use crate::streaming::session::Session;
+use crate::streaming::streams;
 use anyhow::Result;
 use error_set::ErrContext;
 use iggy_common::IggyError;
@@ -55,7 +56,7 @@ impl ServerCommandHandler for DeleteTopic {
             .await?;
         let stream_id = shard
             .streams2
-            .with_root_by_id(&self.stream_id, |root| root.id());
+            .with_stream_by_id(&self.stream_id, streams::helpers::get_stream_id());
         let topic_id = topic.root().id();
         shard_info!(
             shard.id,
diff --git a/core/server/src/binary/handlers/topics/get_topic_handler.rs b/core/server/src/binary/handlers/topics/get_topic_handler.rs
index 7c815a43..52d60836 100644
--- a/core/server/src/binary/handlers/topics/get_topic_handler.rs
+++ b/core/server/src/binary/handlers/topics/get_topic_handler.rs
@@ -22,6 +22,7 @@ use crate::binary::mapper;
 use crate::binary::sender::SenderKind;
 use crate::shard::IggyShard;
 use crate::streaming::session::Session;
+use crate::streaming::streams;
 use anyhow::Result;
 use iggy_common::IggyError;
 use iggy_common::get_topic::GetTopic;
@@ -43,15 +44,14 @@ impl ServerCommandHandler for GetTopic {
         debug!("session: {session}, command: {self}");
         shard.ensure_authenticated(session)?;
         shard.ensure_topic_exists(&self.stream_id, &self.topic_id)?;
-        shard
+        let numeric_stream_id = shard
             .streams2
-            .with_root_by_id(&self.stream_id, |stream_root| {
-                shard.permissioner.borrow().get_topic(
-                    session.get_user_id(),
-                    stream_root.id() as u32,
-                    self.topic_id.get_u32_value().unwrap_or(0),
-                )
-            })?;
+            .with_stream_by_id(&self.stream_id, streams::helpers::get_stream_id());
+        shard.permissioner.borrow().get_topic(
+            session.get_user_id(),
+            numeric_stream_id as u32,
+            self.topic_id.get_u32_value().unwrap_or(0),
+        );
 
         shard
             .streams2
diff --git a/core/server/src/binary/handlers/topics/get_topics_handler.rs b/core/server/src/binary/handlers/topics/get_topics_handler.rs
index 69a586a0..2c49571a 100644
--- a/core/server/src/binary/handlers/topics/get_topics_handler.rs
+++ b/core/server/src/binary/handlers/topics/get_topics_handler.rs
@@ -23,6 +23,7 @@ use crate::binary::sender::SenderKind;
 use crate::shard::IggyShard;
 use crate::slab::traits_ext::{EntityComponentSystem, IntoComponents};
 use crate::streaming::session::Session;
+use crate::streaming::streams;
 use anyhow::Result;
 use iggy_common::IggyError;
 use iggy_common::get_topics::GetTopics;
@@ -44,18 +45,19 @@ impl ServerCommandHandler for GetTopics {
         debug!("session: {session}, command: {self}");
         shard.ensure_authenticated(session)?;
         shard.ensure_stream_exists(&self.stream_id)?;
-        shard.streams2.with_root_by_id(&self.stream_id, |root| {
-            shard
-                .permissioner
-                .borrow()
-                .get_topics(session.get_user_id(), root.id() as u32)
-        })?;
+        let numeric_stream_id = shard
+            .streams2
+            .with_stream_by_id(&self.stream_id, streams::helpers::get_stream_id());
+        shard
+            .permissioner
+            .borrow()
+            .get_topics(session.get_user_id(), numeric_stream_id as u32);
 
         shard
             .streams2
             .with_topics_async(&self.stream_id, async |topics| {
                 topics
-                    .with_async(async |topics| {
+                    .with_components_async(async |topics| {
                         let (roots, stats) = topics.into_components();
                         let response = mapper::map_topics(&roots, &stats);
                         sender.send_ok_response(&response).await
diff --git a/core/server/src/binary/handlers/topics/purge_topic_handler.rs b/core/server/src/binary/handlers/topics/purge_topic_handler.rs
index 101c7973..63d0daa0 100644
--- a/core/server/src/binary/handlers/topics/purge_topic_handler.rs
+++ b/core/server/src/binary/handlers/topics/purge_topic_handler.rs
@@ -47,7 +47,7 @@ impl ServerCommandHandler for PurgeTopic {
         let stream_id = self.stream_id.clone();
 
         shard
-            .purge_topic(session, &self.stream_id, &self.topic_id)
+            .purge_topic2(session, &self.stream_id, &self.topic_id)
             .await
             .with_error_context(|error| {
                 format!(
diff --git a/core/server/src/binary/handlers/topics/update_topic_handler.rs b/core/server/src/binary/handlers/topics/update_topic_handler.rs
index 8d3acc6b..8a5e7595 100644
--- a/core/server/src/binary/handlers/topics/update_topic_handler.rs
+++ b/core/server/src/binary/handlers/topics/update_topic_handler.rs
@@ -23,6 +23,7 @@ use crate::shard::IggyShard;
 use crate::shard::transmission::event::ShardEvent;
 use crate::state::command::EntryCommand;
 use crate::streaming::session::Session;
+use crate::streaming::topics;
 use anyhow::Result;
 use error_set::ErrContext;
 use iggy_common::IggyError;
@@ -54,18 +55,16 @@ impl ServerCommandHandler for UpdateTopic {
             self.max_topic_size,
             self.replication_factor,
         );
-        self.message_expiry =
-            shard
-                .streams2
-                .with_topic_root_by_id(&self.stream_id, &self.topic_id, |root| {
-                    root.message_expiry()
-                });
-        self.max_topic_size =
-            shard
-                .streams2
-                .with_topic_root_by_id(&self.stream_id, &self.topic_id, |root| {
-                    root.max_topic_size()
-                });
+        self.message_expiry = shard.streams2.with_topic_by_id(
+            &self.stream_id,
+            &self.topic_id,
+            topics::helpers::get_message_expiry(),
+        );
+        self.max_topic_size = shard.streams2.with_topic_by_id(
+            &self.stream_id,
+            &self.topic_id,
+            topics::helpers::get_max_topic_size(),
+        );
         let event = ShardEvent::UpdatedTopic2 {
             stream_id: self.stream_id.clone(),
             topic_id: self.topic_id.clone(),
diff --git a/core/server/src/binary/mapper.rs b/core/server/src/binary/mapper.rs
index 0b2ced4d..26f923f1 100644
--- a/core/server/src/binary/mapper.rs
+++ b/core/server/src/binary/mapper.rs
@@ -186,8 +186,7 @@ pub fn map_topics(roots: &Slab<TopicRoot>, stats: &Slab<Arc<TopicStats>>) -> Byt
 pub fn map_topic(root: &topic2::TopicRoot, stats: &TopicStats) -> Bytes {
     let mut bytes = BytesMut::new();
     extend_topic(root, stats, &mut bytes);
-
-    root.partitions().with(|partitions| {
+    root.partitions().with_components(|partitions| {
         let (roots, stats, _, offsets, _, _) = partitions.into_components();
         for (root, stat, offset) in roots
             .iter()
diff --git a/core/server/src/shard/mod.rs b/core/server/src/shard/mod.rs
index 7e75127a..031bbe44 100644
--- a/core/server/src/shard/mod.rs
+++ b/core/server/src/shard/mod.rs
@@ -525,6 +525,8 @@ impl IggyShard {
     }
 
     async fn handle_request(&self, request: ShardRequest) -> Result<ShardResponse, IggyError> {
+        todo!();
+        /*
         let stream = self.get_stream(&Identifier::numeric(request.stream_id)?)?;
         let topic = stream.get_topic(&Identifier::numeric(request.topic_id)?)?;
         let partition_id = request.partition_id;
@@ -540,13 +542,13 @@ impl IggyShard {
                 Ok(ShardResponse::PollMessages((metadata, batch)))
             }
         }
+        */
     }
 
     async fn handle_event(&self, event: ShardEvent) -> Result<(), IggyError> {
         match event {
             ShardEvent::CreatedStream { stream_id, name } => {
-                self.create_stream_bypass_auth(stream_id, &name)?;
-                Ok(())
+                todo!();
             }
             ShardEvent::CreatedTopic {
                 stream_id,
@@ -576,44 +578,14 @@ impl IggyShard {
                 topic_id,
                 partition_ids,
             } => {
-                let records = self
-                    .create_shard_table_records(&partition_ids, stream_id, topic_id)
-                    .collect::<Vec<_>>();
-                let stream = self.get_stream(&Identifier::numeric(stream_id)?)?;
-                let topic = stream.get_topic(&Identifier::numeric(topic_id)?)?;
-                // Open partition and segments for that particular shard.
-                for (ns, shard_info) in records.iter() {
-                    if shard_info.id() == self.id {
-                        let partition_id = ns.partition_id;
-                        let partition = topic.get_partition(partition_id)?;
-                        let mut partition = partition.write().await;
-                        partition.open().await.with_error_context(|error| {
-                                                                                                            format!(
-                                                                                                                "{COMPONENT} (error: {error}) - failed to open partition with ID: {partition_id} in topic with ID: {topic_id} for stream with ID: {stream_id}"
-                                                                                                            )
-                                                                                                        })?;
-                    }
-                }
-                self.insert_shard_table_records(records);
-                Ok(())
+                todo!();
             }
             ShardEvent::CreatedPartitions {
                 stream_id,
                 topic_id,
                 partitions_count,
             } => {
-                let mut stream = self.get_stream_mut(&stream_id)?;
-                let topic = stream.get_topic_mut(&topic_id)?;
-                topic.add_persisted_partitions(partitions_count)
-                                                                                                    .with_error_context(|error| {
-                                                                                                        format!(
-                                                                                                            "{COMPONENT} (error: {error}) - failed to create partitions for topic with ID: {topic_id} in stream with ID: {stream_id}"
-                                                                                                        )
-                                                                                                    })?;
-                topic.reassign_consumer_groups();
-                self.metrics.increment_partitions(partitions_count);
-                self.metrics.increment_segments(partitions_count);
-                Ok(())
+                todo!();
             }
             ShardEvent::DeletedPartitions2 {
                 stream_id,
@@ -765,7 +737,7 @@ impl IggyShard {
                 Ok(())
             }
             ShardEvent::CreatedTopic2 { stream_id, topic } => {
-                let _topic_id = self.create_topic2_bypass_auth(&stream_id, topic)?;
+                let _topic_id = self.create_topic2_bypass_auth(&stream_id, topic);
                 Ok(())
             }
             ShardEvent::CreatedPartitions2 {
diff --git a/core/server/src/shard/system/consumer_groups.rs b/core/server/src/shard/system/consumer_groups.rs
index 2283fbb4..a0dec7a6 100644
--- a/core/server/src/shard/system/consumer_groups.rs
+++ b/core/server/src/shard/system/consumer_groups.rs
@@ -16,209 +16,87 @@
  * under the License.
  */
 
-use std::cell::Ref;
-
 use super::COMPONENT;
 use crate::shard::IggyShard;
+use crate::slab::consumer_groups;
 use crate::slab::traits_ext::EntityComponentSystem;
+use crate::slab::traits_ext::EntityMarker;
+use crate::slab::traits_ext::Insert;
 use crate::slab::traits_ext::IntoComponents;
+use crate::streaming::partitions;
 use crate::streaming::session::Session;
-use crate::streaming::streams::stream::Stream;
-use crate::streaming::topics::consumer_group::ConsumerGroup;
+use crate::streaming::streams;
+use crate::streaming::topics;
 use crate::streaming::topics::consumer_group2;
 use crate::streaming::topics::consumer_group2::MEMBERS_CAPACITY;
-use crate::streaming::topics::consumer_group2::Member;
-use ahash::AHashMap;
 use arcshift::ArcShift;
 use error_set::ErrContext;
 use iggy_common::Identifier;
 use iggy_common::IggyError;
-use iggy_common::locking::IggyRwLockFn;
 use slab::Slab;
 
 impl IggyShard {
-    pub fn get_consumer_group<'cg, 'stream>(
-        &self,
-        session: &Session,
-        stream: &'stream Stream,
-        topic_id: &Identifier,
-        group_id: &Identifier,
-    ) -> Result<Option<Ref<'cg, ConsumerGroup>>, IggyError>
-    where
-        'stream: 'cg,
-    {
-        self.ensure_authenticated(session)?;
-        let stream_id = stream.stream_id;
-        let topic = stream.get_topic(topic_id).with_error_context(|error| {
-            format!(
-                "{COMPONENT} (error: {error}) - topic with ID: {topic_id} was not found in stream with ID: {stream_id}",
-            )
-        })?;
-
-        self.permissioner
-        .borrow()
-            .get_consumer_group(session.get_user_id(), topic.stream_id, topic.topic_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - permission denied to get consumer group with ID: {group_id} for user with ID: {} in topic with ID: {topic_id} and stream with ID: {stream_id}",
-                    session.get_user_id(),
-                )
-            })?;
-
-        topic.try_get_consumer_group(group_id)
-    }
-
-    pub fn get_consumer_groups(
-        &self,
-        session: &Session,
-        stream_id: &Identifier,
-        topic_id: &Identifier,
-    ) -> Result<Vec<ConsumerGroup>, IggyError> {
-        self.ensure_authenticated(session)?;
-        let stream = self.get_stream(stream_id).with_error_context(|error| {
-            format!("{COMPONENT} (error: {error}) - stream with ID: {stream_id} was not found")
-        })?;
-        let topic = self.find_topic(session, &stream, topic_id)
-            .with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic with ID: {topic_id} was not found in stream with ID: {stream_id}"))?;
-
-        self.permissioner
-        .borrow()
-            .get_consumer_groups(session.get_user_id(), topic.stream_id, topic.topic_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - permission denied to get consumer groups in topic with ID: {topic_id} and stream with ID: {stream_id} for user with ID: {}",
-                    session.get_user_id(),
-                )
-            })?;
-
-        Ok(topic.get_consumer_groups())
-    }
-
-    pub fn create_consumer_group_bypass_auth(
-        &self,
-        stream_id: &Identifier,
-        topic_id: &Identifier,
-        group_id: Option<u32>,
-        name: &str,
-    ) -> Result<(), IggyError> {
-        self.create_consumer_group_base(stream_id, topic_id, group_id, name)?;
-        Ok(())
-    }
-
     pub fn create_consumer_group2(
         &self,
         session: &Session,
         stream_id: &Identifier,
         topic_id: &Identifier,
-        members: ArcShift<Slab<Member>>,
-        group_id: Option<u32>,
         name: String,
-    ) -> Result<usize, IggyError> {
+    ) -> Result<consumer_group2::ConsumerGroup, IggyError> {
         self.ensure_authenticated(session)?;
         self.ensure_topic_exists(stream_id, topic_id)?;
         {
-            let topic_id = self
-                .streams2
-                .with_topic_root_by_id(stream_id, topic_id, |topic| topic.id());
+            let topic_id = self.streams2.with_topic_by_id(
+                stream_id,
+                topic_id,
+                topics::helpers::get_topic_id(),
+            );
             let stream_id = self
                 .streams2
-                .with_root_by_id(stream_id, |stream| stream.id());
+                .with_stream_by_id(stream_id, streams::helpers::get_stream_id());
             self.permissioner.borrow().create_consumer_group(
                 session.get_user_id(),
                 stream_id as u32,
                 topic_id as u32,
             ).with_error_context(|error| format!("{COMPONENT} (error: {error}) - permission denied to create consumer group for user {} on stream ID: {}, topic ID: {}", session.get_user_id(), stream_id, topic_id))?;
         }
-        self.create_consumer_group_base2(stream_id, topic_id, members, name)
-    }
-
-    pub fn create_consumer_group_bypass_auth2(
-        &self,
-        stream_id: &Identifier,
-        topic_id: &Identifier,
-        members: ArcShift<Slab<Member>>,
-        name: String,
-    ) -> Result<usize, IggyError> {
-        self.create_consumer_group_base2(stream_id, topic_id, members, name)
+        let cg = self.create_and_insert_consumer_group_mem(stream_id, topic_id, name);
+        Ok(cg)
     }
 
-    fn create_consumer_group_base2(
+    fn create_and_insert_consumer_group_mem(
         &self,
         stream_id: &Identifier,
         topic_id: &Identifier,
-        members: ArcShift<Slab<Member>>,
         name: String,
-    ) -> Result<usize, IggyError> {
-        let id = self
-            .streams2
-            .with_topic_root_by_id_mut(stream_id, topic_id, |topic| {
-                let partitions = topic.partitions().with(|partitions| {
-                    let (info, _, _, _, _, _) = partitions.into_components();
-                    info.iter()
-                        .map(|(_, partition)| partition.id())
-                        .collect::<Vec<_>>()
-                });
-                topic.consumer_groups_mut().with_mut(|container| {
-                    let cg = consumer_group2::ConsumerGroup::new(name, members.clone(), partitions);
-                    cg.insert_into(container)
-                })
-            });
-        Ok(id)
-    }
-
-    pub fn create_consumer_group(
-        &self,
-        session: &Session,
-        stream_id: &Identifier,
-        topic_id: &Identifier,
-        group_id: Option<u32>,
-        name: &str,
-    ) -> Result<Identifier, IggyError> {
-        self.ensure_authenticated(session)?;
-        {
-            let stream = self.get_stream(stream_id).with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - stream not found for stream ID: {stream_id}"
-                )
-            })?;
-            let topic = self.find_topic(session, &stream, topic_id)
-                .with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id}, topic_id: {topic_id}"))?;
-
-            self.permissioner.borrow().create_consumer_group(
-                session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id,
-            ).with_error_context(|error| format!("{COMPONENT} (error: {error}) - permission denied to create consumer group for user {} on stream ID: {}, topic ID: {}", session.get_user_id(), topic.stream_id, topic.topic_id))?;
-        }
-        self.create_consumer_group_base(stream_id, topic_id, group_id, name)
+    ) -> consumer_group2::ConsumerGroup {
+        let partitions = self.streams2.with_topics(stream_id, |topics| {
+            topics.with_partitions(topic_id, partitions::helpers::get_partition_ids())
+        });
+        let members = ArcShift::new(Slab::with_capacity(MEMBERS_CAPACITY));
+        let mut cg = consumer_group2::ConsumerGroup::new(name, members, partitions);
+        let id = self.insert_consumer_group_mem(stream_id, topic_id, cg.clone());
+        cg.update_id(id);
+        cg
     }
 
-    fn create_consumer_group_base(
+    fn insert_consumer_group_mem(
         &self,
         stream_id: &Identifier,
         topic_id: &Identifier,
-        group_id: Option<u32>,
-        name: &str,
-    ) -> Result<Identifier, IggyError> {
-        let mut stream = self.get_stream_mut(stream_id)
-            .with_error_context(|error| format!("{COMPONENT} (error: {error}) - failed to get mutable reference to stream with ID: {stream_id}"))?;
-        let topic = stream.get_topic_mut(topic_id)
-            .with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id}, topic_id: {topic_id}"))?;
-
-        topic
-            .create_consumer_group(group_id, name)
-            .with_error_context(|error| {
-                format!("{COMPONENT} (error: {error}) - failed to create consumer group with name: {name}")
-            })
+        cg: consumer_group2::ConsumerGroup,
+    ) -> consumer_groups::ContainerId {
+        self.streams2
+            .with_consumer_groups_mut(stream_id, topic_id, |container| container.insert(cg))
     }
 
-    pub fn delete_consumer_group_bypass_auth(
+    pub fn create_consumer_group_bypass_auth2(
         &self,
         stream_id: &Identifier,
         topic_id: &Identifier,
-        consumer_group_id: &Identifier,
-    ) -> Result<ConsumerGroup, IggyError> {
-        self.delete_consumer_group_base(stream_id, topic_id, consumer_group_id)
+        cg: consumer_group2::ConsumerGroup,
+    ) -> usize {
+        self.insert_consumer_group_mem(stream_id, topic_id, cg)
     }
 
     pub fn delete_consumer_group2(
@@ -229,21 +107,24 @@ impl IggyShard {
         group_id: &Identifier,
     ) -> Result<consumer_group2::ConsumerGroup, IggyError> {
         self.ensure_authenticated(session)?;
-        //self.ensure_consumer_group_exists(stream_id, topic_id, group_id)?;
+        self.ensure_consumer_group_exists(stream_id, topic_id, group_id)?;
         {
-            let topic_id = self
-                .streams2
-                .with_topic_root_by_id(stream_id, topic_id, |topic| topic.id());
+            let topic_id = self.streams2.with_topic_by_id(
+                stream_id,
+                topic_id,
+                topics::helpers::get_topic_id(),
+            );
             let stream_id = self
                 .streams2
-                .with_root_by_id(stream_id, |stream| stream.id());
+                .with_stream_by_id(stream_id, streams::helpers::get_stream_id());
             self.permissioner.borrow().delete_consumer_group(
                 session.get_user_id(),
                 stream_id as u32,
                 topic_id as u32,
             ).with_error_context(|error| format!("{COMPONENT} (error: {error}) - permission denied to delete consumer group for user {} on stream ID: {}, topic ID: {}", session.get_user_id(), stream_id, topic_id))?;
         }
-        self.delete_consumer_group_base2(stream_id, topic_id, group_id)
+        let cg = self.delete_consumer_group_base2(stream_id, topic_id, group_id);
+        Ok(cg)
     }
 
     pub fn delete_consumer_group_bypass_auth2(
@@ -251,7 +132,7 @@ impl IggyShard {
         stream_id: &Identifier,
         topic_id: &Identifier,
         group_id: &Identifier,
-    ) -> Result<consumer_group2::ConsumerGroup, IggyError> {
+    ) -> consumer_group2::ConsumerGroup {
         self.delete_consumer_group_base2(stream_id, topic_id, group_id)
     }
 
@@ -260,104 +141,13 @@ impl IggyShard {
         stream_id: &Identifier,
         topic_id: &Identifier,
         group_id: &Identifier,
-    ) -> Result<consumer_group2::ConsumerGroup, IggyError> {
-        let cg = self
-            .streams2
-            .with_topic_root_by_id_mut(stream_id, topic_id, |root| {
-                match group_id.kind {
-                    iggy_common::IdKind::Numeric => {
-                        root.consumer_groups_mut().with_mut(|container| {
-                            container.try_remove(group_id.get_u32_value().unwrap() as usize)
-                        })
-                    }
-                    iggy_common::IdKind::String => {
-                        let key = group_id.get_string_value().unwrap();
-                        let id = root
-                            .consumer_groups()
-                            .with_index(|index| *(index.get(&key).unwrap()));
-                        root.consumer_groups_mut()
-                            .with_mut(|container| container.try_remove(id))
-                    }
-                }
-                // TODO: Fix
-            })
-            .ok_or_else(|| IggyError::ConsumerGroupIdNotFound(0, 0))?;
-        Ok(cg)
-    }
-
-    pub async fn delete_consumer_group(
-        &self,
-        session: &Session,
-        stream_id: &Identifier,
-        topic_id: &Identifier,
-        consumer_group_id: &Identifier,
-    ) -> Result<(), IggyError> {
-        self.ensure_authenticated(session)?;
-        {
-            let stream = self.get_stream(stream_id).with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - stream not found for stream ID: {stream_id}"
-                )
-            })?;
-            let topic = self.find_topic(session, &stream, topic_id)
-                .with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id}, topic_id: {topic_id}"))?;
-
-            self.permissioner.borrow().delete_consumer_group(
-                session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id,
-            ).with_error_context(|error| format!("{COMPONENT} (error: {error}) - permission denied to delete consumer group for user {} on stream ID: {}, topic ID: {}", session.get_user_id(), topic.stream_id, topic.topic_id))?;
-        }
-        let cg = self.delete_consumer_group_base(stream_id, topic_id, consumer_group_id)?;
-        let stream = self.get_stream(stream_id)?;
-        let topic = stream.get_topic(topic_id)?;
-
-        for (_, partition) in topic.partitions.iter() {
-            let partition = partition.read().await;
-            if let Some((_, offset)) = partition.consumer_group_offsets.remove(&cg.group_id) {
-                self.storage
-                    .partition
-                    .delete_consumer_offset(&offset.path)
-                    .await?;
-            }
-        }
-
-        Ok(())
-    }
-
-    fn delete_consumer_group_base(
-        &self,
-        stream_id: &Identifier,
-        topic_id: &Identifier,
-        consumer_group_id: &Identifier,
-    ) -> Result<ConsumerGroup, IggyError> {
-        let stream_id_value;
-        let topic_id_value;
-        let consumer_group;
-        {
-            let mut stream = self.get_stream_mut(stream_id).with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to get mutable reference to stream with id: {stream_id}"
-                )
-            })?;
-            let topic = stream.get_topic_mut(topic_id).with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id}, topic_id: {topic_id}"))?;
-
-            consumer_group = topic.delete_consumer_group(consumer_group_id)
-                .with_error_context(|error| format!("{COMPONENT} (error: {error}) - failed to delete consumer group with ID: {consumer_group_id}"))?;
-            stream_id_value = topic.stream_id;
-            topic_id_value = topic.topic_id;
-        }
-
-        for member in consumer_group.get_members() {
-            self.client_manager.borrow_mut().leave_consumer_group(
-                    member.id,
-                    stream_id_value,
-                    topic_id_value,
-                    consumer_group.group_id,
-                )
-                .with_error_context(|error| format!("{COMPONENT} (error: {error}) - failed to make client leave consumer group for client ID: {}, group ID: {}", member.id, consumer_group.group_id))?;
-        }
-        Ok(consumer_group)
+    ) -> consumer_group2::ConsumerGroup {
+        self.streams2.with_consumer_groups_mut(
+            stream_id,
+            topic_id,
+            topics::helpers::delete_consumer_group(group_id),
+        )
+        // TODO: remove from the consumer_group
     }
 
     pub fn join_consumer_group(
@@ -365,67 +155,35 @@ impl IggyShard {
         session: &Session,
         stream_id: &Identifier,
         topic_id: &Identifier,
-        consumer_group_id: &Identifier,
+        group_id: &Identifier,
     ) -> Result<(), IggyError> {
         self.ensure_authenticated(session)?;
-        let stream_id_value;
-        let topic_id_value;
+        self.ensure_consumer_group_exists(stream_id, topic_id, group_id)?;
         {
-            let stream = self.get_stream(stream_id).with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - stream not found for stream ID: {stream_id}"
-                )
-            })?;
-            let topic = self
-                .find_topic(session, &stream, topic_id)
-                .with_error_context(|error| {
-                    format!(
-                        "{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id}, topic_id: {topic_id}",
-                    )
-                })?;
-
+            let topic_id = self.streams2.with_topic_by_id(
+                &stream_id,
+                topic_id,
+                topics::helpers::get_topic_id(),
+            );
+            let stream_id = self
+                .streams2
+                .with_stream_by_id(stream_id, streams::helpers::get_stream_id());
             self.permissioner.borrow().join_consumer_group(
                 session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id,
-            ).with_error_context(|error| format!("{COMPONENT} (error: {error}) - permission denied to join consumer group for user {} on stream ID: {}, topic ID: {}", session.get_user_id(), topic.stream_id, topic.topic_id))?;
-
-            stream_id_value = topic.stream_id;
-            topic_id_value = topic.topic_id;
-        }
-
-        let group_id;
-        {
-            let mut stream = self.get_stream_mut(stream_id)
-                .with_error_context(|error| {
-                    format!("{COMPONENT} (error: {error}) - failed to get mutable reference to stream with ID: {stream_id}")
-                })?;
-            let topic = stream.get_topic_mut(topic_id)
-                .with_error_context(|error| {
-                    format!("{COMPONENT} (error: {error}) - failed to get mutable reference to topic with ID: {topic_id}")
-                })?;
-
-            {
-                let consumer_group = topic
-                    .get_consumer_group(consumer_group_id)
-                    .with_error_context(|error| {
-                        format!(
-                            "{COMPONENT} (error: {error}) - consumer group not found for group_id: {consumer_group_id:?}"
-                        )
-                    })?;
-
-                group_id = consumer_group.group_id;
-            }
-
-            topic
-                .join_consumer_group(consumer_group_id, session.client_id)
-                .with_error_context(|error| {
-                    format!(
-                        "{COMPONENT} (error: {error}) - failed to join consumer group for group ID: {group_id}"
-                    )
-                })?;
+                stream_id as u32,
+                topic_id as u32,
+            ).with_error_context(|error| format!("{COMPONENT} (error: {error}) - permission denied to join consumer group for user {} on stream ID: {}, topic ID: {}", session.get_user_id(), stream_id, topic_id))?;
         }
+        let client_id = session.client_id;
+        self.streams2.with_consumer_group_by_id_mut(
+            stream_id,
+            topic_id,
+            group_id,
+            topics::helpers::join_consumer_group(self.id, client_id),
+        );
 
+        // TODO:
+        /*
         self.client_manager.borrow_mut().join_consumer_group(session.client_id, stream_id_value, topic_id_value, group_id)
             .with_error_context(|error| {
                 format!(
@@ -433,7 +191,7 @@ impl IggyShard {
                     session.client_id
                 )
             })?;
-
+            */
         Ok(())
     }
 
@@ -445,37 +203,7 @@ impl IggyShard {
         consumer_group_id: &Identifier,
     ) -> Result<(), IggyError> {
         self.ensure_authenticated(session)?;
-        {
-            let stream = self.get_stream(stream_id).with_error_context(|error| {
-                format!("{COMPONENT} (error: {error}) - failed to get stream with ID: {stream_id}")
-            })?;
-            let topic = self
-                .find_topic(session, &stream, topic_id)
-                .with_error_context(|error| {
-                    format!(
-                        "{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id:?}, topic_id: {topic_id:?}"
-                    )
-                })?;
-
-            self.permissioner.borrow().leave_consumer_group(
-                session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id,
-            ).with_error_context(|error| format!("{COMPONENT} (error: {error}) - permission denied to leave consumer group for user {} on stream ID: {}, topic ID: {}", session.get_user_id(), topic.stream_id, topic.topic_id))?;
-        }
-
-        self.leave_consumer_group_by_client(
-            stream_id,
-            topic_id,
-            consumer_group_id,
-            session.client_id,
-        )
-        .with_error_context(|error| {
-            format!(
-                "{COMPONENT} (error: {error}) - failed to leave consumer group for client ID: {}",
-                session.client_id
-            )
-        })
+        todo!();
     }
 
     pub fn leave_consumer_group_by_client(
@@ -485,47 +213,15 @@ impl IggyShard {
         consumer_group_id: &Identifier,
         client_id: u32,
     ) -> Result<(), IggyError> {
-        let stream_id_value;
-        let topic_id_value;
-        let group_id;
-
-        {
-            let mut stream = self.get_stream_mut(stream_id).with_error_context(|error| {
-                format!("{COMPONENT} (error: {error}) - failed to get stream with ID: {stream_id}")
-            })?;
-            let stream_id = stream.stream_id;
-            let topic = stream.get_topic_mut(topic_id)
-                .with_error_context(|error| {
-                    format!(
-                        "{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id}, topic_id: {topic_id}",
-                    )
-                })?;
-            let topic_id = topic.topic_id;
-            {
-                let consumer_group = topic
-                    .get_consumer_group(consumer_group_id)
-                    .with_error_context(|error| {
-                        format!(
-                        "{COMPONENT} (error: {error}) - consumer group not found for group_id: {consumer_group_id}",
-                    )
-                    })?;
-                group_id = consumer_group.group_id;
-            }
-
-            stream_id_value = stream_id;
-            topic_id_value = topic_id;
-            topic
-                .leave_consumer_group(consumer_group_id, client_id)
-                .with_error_context(|error| {
-                    format!("{COMPONENT} (error: {error}) - failed leave consumer group, client ID {client_id}",)
-                })?;
-        }
+        todo!();
 
+        /*
         self.client_manager.borrow_mut().leave_consumer_group(
             client_id,
             stream_id_value,
             topic_id_value,
             group_id,
         )
+        */
     }
 }
diff --git a/core/server/src/shard/system/consumer_offsets.rs b/core/server/src/shard/system/consumer_offsets.rs
index f2ed0a84..c3afcb30 100644
--- a/core/server/src/shard/system/consumer_offsets.rs
+++ b/core/server/src/shard/system/consumer_offsets.rs
@@ -32,6 +32,8 @@ impl IggyShard {
         offset: u64,
     ) -> Result<(), IggyError> {
         self.ensure_authenticated(session)?;
+        todo!();
+        /*
         let stream = self.get_stream(stream_id).with_error_context(|error| {
             format!("{COMPONENT} (error: {error}) - stream with ID: {stream_id} was not found")
         })?;
@@ -46,6 +48,7 @@ impl IggyShard {
         topic
             .store_consumer_offset(consumer, offset, partition_id, session.client_id)
             .await
+            */
     }
 
     pub async fn get_consumer_offset(
@@ -57,6 +60,8 @@ impl IggyShard {
         partition_id: Option<u32>,
     ) -> Result<Option<ConsumerOffsetInfo>, IggyError> {
         self.ensure_authenticated(session)?;
+        todo!();
+        /*
         let stream = self.get_stream(stream_id).with_error_context(|error| {
             format!("{COMPONENT} (error: {error}) - stream with ID: {stream_id} was not found")
         })?;
@@ -78,6 +83,7 @@ impl IggyShard {
         topic
             .get_consumer_offset(consumer, partition_id, session.client_id)
             .await
+            */
     }
 
     pub async fn delete_consumer_offset(
@@ -89,6 +95,8 @@ impl IggyShard {
         partition_id: Option<u32>,
     ) -> Result<(), IggyError> {
         self.ensure_authenticated(session)?;
+        todo!();
+        /*
         let stream = self.get_stream(stream_id).with_error_context(|error| {
             format!("{COMPONENT} (error: {error}) - stream with ID: {stream_id} was not found")
         })?;
@@ -108,5 +116,6 @@ impl IggyShard {
         topic
             .delete_consumer_offset(consumer, partition_id, session.client_id)
             .await
+            */
     }
 }
diff --git a/core/server/src/shard/system/messages.rs b/core/server/src/shard/system/messages.rs
index c5e527d0..51e37d84 100644
--- a/core/server/src/shard/system/messages.rs
+++ b/core/server/src/shard/system/messages.rs
@@ -46,6 +46,8 @@ impl IggyShard {
         partitioning: &Partitioning,
         batch: IggyMessagesBatchMut,
     ) -> Result<(), IggyError> {
+        todo!();
+        /*
         let stream = self.get_stream(stream_id).with_error_context(|error| {
             format!(
                 "Failed to get stream with ID: {} (error: {})",
@@ -119,6 +121,7 @@ impl IggyShard {
 
         self.metrics.increment_messages(messages_count as u64);
         Ok(())
+        */
     }
 
     pub async fn poll_messages(
@@ -131,6 +134,8 @@ impl IggyShard {
         maybe_partition_id: Option<u32>,
         args: PollingArgs,
     ) -> Result<(IggyPollMetadata, IggyMessagesBatchSet), IggyError> {
+        todo!();
+        /*
         let stream = self.get_stream(stream_id).with_error_context(|error| {
             format!(
                 "{COMPONENT} (error: {error}) - stream not found for stream ID: {}",
@@ -208,6 +213,7 @@ impl IggyShard {
         };
 
         Ok((metadata, batch))
+        */
     }
 
     pub async fn flush_unsaved_buffer(
@@ -219,23 +225,7 @@ impl IggyShard {
         fsync: bool,
     ) -> Result<(), IggyError> {
         self.ensure_authenticated(session)?;
-        let stream = self.get_stream(&stream_id).with_error_context(|error| {
-            format!("{COMPONENT} (error: {error}) - stream not found for stream ID: {stream_id}")
-        })?;
-        let stream_id = stream.stream_id;
-        let topic = self.find_topic(session, &stream, &topic_id).with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id}, topic ID: {topic_id}"))?;
-        self.permissioner.borrow().append_messages(
-            session.get_user_id(),
-            topic.stream_id,
-            topic.topic_id
-        ).with_error_context(|error| format!(
-            "{COMPONENT} (error: {error}) - permission denied to append messages for user {} on stream ID: {}, topic ID: {}",
-            session.get_user_id(),
-            topic.stream_id,
-            topic.topic_id
-        ))?;
-        topic.flush_unsaved_buffer(partition_id, fsync).await?;
-        Ok(())
+        todo!();
     }
 
     pub fn maybe_encrypt_messages(
diff --git a/core/server/src/shard/system/partitions.rs b/core/server/src/shard/system/partitions.rs
index dfd9efe4..b0ec8ec0 100644
--- a/core/server/src/shard/system/partitions.rs
+++ b/core/server/src/shard/system/partitions.rs
@@ -16,30 +16,23 @@
  * under the License.
  */
 
-use std::error;
-use std::sync::Arc;
-
 use super::COMPONENT;
 use crate::configs::system::SystemConfig;
 use crate::shard::IggyShard;
-use crate::slab::traits_ext::Delete;
-use crate::slab::traits_ext::EntityComponentSystem;
 use crate::slab::traits_ext::EntityMarker;
-use crate::slab::traits_ext::Insert;
 use crate::streaming::deduplication::message_deduplicator::MessageDeduplicator;
-use crate::streaming::partitions::partition::Partition;
 use crate::streaming::partitions::partition2;
 use crate::streaming::partitions::storage2::create_partition_file_hierarchy;
 use crate::streaming::session::Session;
 use crate::streaming::stats::stats::PartitionStats;
 use crate::streaming::stats::stats::TopicStats;
+use crate::streaming::streams;
+use crate::streaming::topics;
 use error_set::ErrContext;
 use iggy_common::Identifier;
 use iggy_common::IggyError;
 use iggy_common::IggyTimestamp;
-use iggy_common::delete_partitions;
-use iggy_common::locking::IggyRwLockFn;
-use serde::de;
+use std::sync::Arc;
 use std::sync::atomic::AtomicU64;
 
 impl IggyShard {
@@ -75,28 +68,24 @@ impl IggyShard {
         partitions_count: u32,
     ) -> Result<Vec<partition2::Partition>, IggyError> {
         self.ensure_authenticated(session)?;
-        /*
-        self.ensure_stream_exists(stream_id)?;
         self.ensure_topic_exists(stream_id, topic_id)?;
-        */
-        let numeric_stream_id =
-            self.streams2
-                .with_root_by_id(stream_id, |stream| stream.id()) as u32;
+        let numeric_stream_id = self
+            .streams2
+            .with_stream_by_id(stream_id, streams::helpers::get_stream_id());
         let numeric_topic_id =
             self.streams2
-                .with_topic_root_by_id(stream_id, topic_id, |topic| topic.id()) as u32;
+                .with_topic_by_id(stream_id, topic_id, topics::helpers::get_topic_id());
 
+        // Claude garbage, rework this.
         self.validate_partition_permissions(
             session,
-            numeric_stream_id,
-            numeric_topic_id,
+            numeric_stream_id as u32,
+            numeric_topic_id as u32,
             "create",
         )?;
-
-        let parent_stats = self.streams2.with_root_by_id(stream_id, |root| {
-            root.topics()
-                .with_stats_by_id(topic_id, |stats| stats.clone())
-        });
+        let parent_stats =
+            self.streams2
+                .with_topic_by_id(stream_id, topic_id, topics::helpers::get_stats());
         let partitions = self.create_and_insert_partitions_mem(
             stream_id,
             topic_id,
@@ -127,18 +116,17 @@ impl IggyShard {
             if !config.message_deduplication.enabled {
                 return None;
             }
-
             let max_entries = if config.message_deduplication.max_entries > 0 {
                 Some(config.message_deduplication.max_entries)
             } else {
                 None
             };
-
             let expiry = if !config.message_deduplication.expiry.is_zero() {
                 Some(config.message_deduplication.expiry)
             } else {
                 None
             };
+
             Some(MessageDeduplicator::new(max_entries, expiry))
         }
 
@@ -175,10 +163,11 @@ impl IggyShard {
         topic_id: &Identifier,
         partition: partition2::Partition,
     ) -> usize {
-        self.streams2
-            .with_topic_root_by_id_mut(stream_id, topic_id, |root| {
-                root.partitions_mut().insert(partition)
-            })
+        self.streams2.with_topic_by_id_mut(
+            stream_id,
+            topic_id,
+            topics::helpers::insert_partition(partition),
+        )
     }
 
     pub fn create_partitions2_bypass_auth(
@@ -198,66 +187,6 @@ impl IggyShard {
         Ok(())
     }
 
-    pub async fn create_partitions(
-        &self,
-        session: &Session,
-        stream_id: &Identifier,
-        topic_id: &Identifier,
-        partitions_count: u32,
-    ) -> Result<Vec<u32>, IggyError> {
-        self.ensure_authenticated(session)?;
-        {
-            let stream = self.get_stream(stream_id).with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - stream not found for stream ID: {stream_id}"
-                )
-            })?;
-            let topic = self.find_topic(session, &stream, topic_id).with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id}, topic ID: {topic_id}"))?;
-            self.permissioner.borrow().create_partitions(
-                session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id,
-            ).with_error_context(|error| format!(
-                "{COMPONENT} (error: {error}) - permission denied to create partitions for user {} on stream ID: {}, topic ID: {}",
-                session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id
-            ))?;
-        }
-
-        let partition_ids = {
-            let mut stream = self.get_stream_mut(stream_id).with_error_context(|error| {
-                format!("{COMPONENT} (error: {error}) - failed to get stream with ID: {stream_id}")
-            })?;
-            let stream_id = stream.stream_id;
-            let topic = stream
-            .get_topic_mut(topic_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to get mutable reference to stream with id: {stream_id}"
-                )
-            })?;
-            let partition_ids = topic
-            .add_persisted_partitions(partitions_count)
-            .with_error_context(|error| {
-                format!("{COMPONENT} (error: {error}) - failed to add persisted partitions, topic: {topic}")
-            })?;
-            partition_ids
-        };
-
-        let mut stream = self.get_stream_mut(stream_id).with_error_context(|error| {
-            format!("{COMPONENT} (error: {error}) - failed to get stream with ID: {stream_id}")
-        })?;
-        let topic = stream.get_topic_mut(topic_id).with_error_context(|error| {
-            format!("{COMPONENT} (error: {error}) - failed to get topic with ID: {topic_id} in stream with ID: {stream_id}")
-        })?;
-
-        topic.reassign_consumer_groups();
-        self.metrics.increment_partitions(partitions_count);
-        self.metrics.increment_segments(partitions_count);
-        Ok(partition_ids)
-    }
-
     pub async fn delete_partitions2(
         &self,
         session: &Session,
@@ -266,23 +195,22 @@ impl IggyShard {
         partitions_count: u32,
     ) -> Result<Vec<u32>, IggyError> {
         self.ensure_authenticated(session)?;
-
-        let numeric_stream_id =
-            self.streams2
-                .with_root_by_id(stream_id, |stream| stream.id()) as u32;
+        let numeric_stream_id = self
+            .streams2
+            .with_stream_by_id(stream_id, streams::helpers::get_stream_id());
         let numeric_topic_id =
             self.streams2
-                .with_topic_root_by_id(stream_id, topic_id, |topic| topic.id()) as u32;
+                .with_topic_by_id(stream_id, topic_id, topics::helpers::get_topic_id());
 
+        // Claude garbage, rework this.
         self.validate_partition_permissions(
             session,
-            numeric_stream_id,
-            numeric_topic_id,
+            numeric_stream_id as u32,
+            numeric_topic_id as u32,
             "delete",
         )?;
         let deleted_partition_ids =
             self.delete_partitions_base2(stream_id, topic_id, partitions_count);
-
         Ok(deleted_partition_ids)
     }
 
@@ -292,22 +220,11 @@ impl IggyShard {
         topic_id: &Identifier,
         partitions_count: u32,
     ) -> Vec<u32> {
-        let deleted_partition_ids =
-            self.streams2
-                .with_topic_root_by_id_mut(stream_id, topic_id, |topic| {
-                    let partitions = topic.partitions_mut();
-                    let current_count = partitions.len() as u32;
-                    let partitions_to_delete = partitions_count.min(current_count);
-                    let start_idx = (current_count - partitions_to_delete) as usize;
-                    let mut deleted_ids = Vec::with_capacity(partitions_to_delete as usize);
-                    for idx in start_idx..current_count as usize {
-                        let partition = topic.partitions_mut().delete(idx);
-                        assert_eq!(partition.id(), idx);
-                        deleted_ids.push(partition.id() as u32);
-                    }
-                    deleted_ids
-                });
-        deleted_partition_ids
+        self.streams2.with_topic_by_id_mut(
+            stream_id,
+            topic_id,
+            topics::helpers::delete_partitions(partitions_count),
+        )
     }
 
     pub fn delete_partitions2_bypass_auth(
@@ -332,78 +249,4 @@ impl IggyShard {
         }
         Ok(())
     }
-
-    pub async fn delete_partitions(
-        &self,
-        session: &Session,
-        stream_id: &Identifier,
-        topic_id: &Identifier,
-        partitions_count: u32,
-    ) -> Result<Vec<u32>, IggyError> {
-        self.ensure_authenticated(session)?;
-        {
-            let stream = self.get_stream(stream_id).with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - stream not found for stream ID: {stream_id}"
-                )
-            })?;
-            let topic = self.find_topic(session, &stream, topic_id).with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream ID: {stream_id}, topic_id: {topic_id}"))?;
-            self.permissioner.borrow().delete_partitions(
-                session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id,
-            ).with_error_context(|error| format!(
-                "{COMPONENT} (error: {error}) - permission denied to delete partitions for user {} on stream ID: {}, topic ID: {}",
-                session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id
-            ))?;
-        }
-
-        let partitions = {
-            let mut stream = self.get_stream_mut(stream_id).with_error_context(|error| {
-                format!("{COMPONENT} (error: {error}) - failed to get stream with ID: {stream_id}")
-            })?;
-            let topic = stream
-            .get_topic_mut(topic_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to get mutable reference to stream with id: {stream_id}"
-                )
-            })?;
-
-            let partitions = topic
-            .delete_persisted_partitions(partitions_count)
-            .with_error_context(|error| {
-                format!("{COMPONENT} (error: {error}) - failed to delete persisted partitions for topic: {topic}")
-            })?;
-            partitions
-        };
-
-        let mut segments_count = 0;
-        let mut messages_count = 0;
-        let mut partition_ids = Vec::with_capacity(partitions.len());
-        for partition in &partitions {
-            let partition = partition.read().await;
-            let partition_id = partition.partition_id;
-            let partition_messages_count = partition.get_messages_count();
-            segments_count += partition.get_segments_count();
-            messages_count += partition_messages_count;
-            partition_ids.push(partition_id);
-        }
-
-        let mut stream = self.get_stream_mut(stream_id).with_error_context(|error| {
-            format!("{COMPONENT} (error: {error}) - failed to get stream with ID: {stream_id}")
-        })?;
-        let topic = stream.get_topic_mut(topic_id).with_error_context(|error| {
-            format!("{COMPONENT} (error: {error}) - failed to get topic with ID: {topic_id}")
-        })?;
-        topic.reassign_consumer_groups();
-        if partitions.len() > 0 {
-            self.metrics.decrement_partitions(partitions_count);
-            self.metrics.decrement_segments(segments_count);
-            self.metrics.decrement_messages(messages_count);
-        }
-        Ok(partition_ids)
-    }
 }
diff --git a/core/server/src/shard/system/segments.rs b/core/server/src/shard/system/segments.rs
index e895f6fd..5b7d69ff 100644
--- a/core/server/src/shard/system/segments.rs
+++ b/core/server/src/shard/system/segments.rs
@@ -34,96 +34,6 @@ impl IggyShard {
     ) -> Result<(), IggyError> {
         // Assert authentication.
         self.ensure_authenticated(session)?;
-
-        {
-            let stream = self.get_stream(stream_id).with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - stream not found for stream_id: {stream_id}"
-                )
-            })?;
-            let topic = self.find_topic(session, &stream, topic_id).with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream_id: {stream_id}, topic_id: {topic_id}"))?;
-
-            self.permissioner.borrow().delete_segments(
-                session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id,
-            ).with_error_context(|error| format!(
-                "{COMPONENT} (error: {error}) - permission denied to delete segments for user {} on Stream ID: {}, Topic ID: {}",
-                session.get_user_id(),
-                topic.stream_id,
-                topic.topic_id
-            ))?;
-        }
-
-        let stream = self.get_stream(stream_id).with_error_context(|error| {
-            format!("{COMPONENT} (error: {error}) - failed to get stream with ID: {stream_id}")
-        })?;
-        let topic = stream
-            .get_topic(topic_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to get mutable reference to stream with ID: {stream_id}"
-                    )
-            })?;
-
-        // Lock the current partition.
-        let partition_lock = topic.get_partition(partition_id)?;
-        let mut partition = partition_lock.write().await;
-
-        partition.segments.sort_by_key(|a| a.start_offset());
-
-        // Retrieve the oldest segments for this partition.
-        let segments = partition
-            .segments
-            .iter()
-            // Filter to only get the closed segments.
-            .filter(|segment| segment.is_closed())
-            .take(
-                segments_count
-                    .try_into()
-                    .map_err(|_| IggyError::InvalidSegmentsCount(segments_count))?,
-            )
-            // coerce to tuple of u64 as this has copy implicit.
-            .map(|segment| (segment.start_offset(), segment.get_messages_count()))
-            .collect::<Vec<_>>();
-
-        // Delete the segments in sequence.
-        let (deleted_segments_count, deleted_messages_count) = {
-            let mut segments_count = 0;
-            let mut messages_count = 0;
-
-            for segment in segments {
-                // delete the segment.
-                let _ = partition.delete_segment(segment.0).await?;
-
-                // increment metrics.
-                segments_count += 1;
-                messages_count += segment.1 as u64;
-            }
-
-            (segments_count, messages_count)
-        };
-        drop(stream);
-        drop(partition);
-
-        let mut stream = self
-            .get_stream_mut(stream_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to get mutable reference to stream with ID: {stream_id}"
-                )
-            })?;
-        let topic = stream
-            .get_topic_mut(topic_id)
-            .with_error_context(|error| {
-                format!(
-                    "{COMPONENT} (error: {error}) - failed to get mutable reference to topic with ID: {topic_id} in stream with ID: {stream_id}"
-                )
-            })?;
-        topic.reassign_consumer_groups();
-
-        self.metrics.decrement_segments(deleted_segments_count);
-        self.metrics.decrement_messages(deleted_messages_count);
-        Ok(())
+        todo!();
     }
 }
diff --git a/core/server/src/shard/system/streams.rs b/core/server/src/shard/system/streams.rs
index 908d81aa..b725c7cf 100644
--- a/core/server/src/shard/system/streams.rs
+++ b/core/server/src/shard/system/streams.rs
@@ -34,7 +34,6 @@ use std::cell::{Ref, RefMut};
 use std::sync::Arc;
 use std::sync::atomic::{AtomicU32, Ordering};
 
-
 impl IggyShard {
     pub async fn create_stream2(
         &self,
@@ -88,7 +87,9 @@ impl IggyShard {
     ) -> Result<(), IggyError> {
         self.ensure_authenticated(session)?;
         self.ensure_stream_exists(stream_id)?;
-        let id = self.streams2.with_stream_by_id(stream_id, streams::helpers::get_stream_id());
+        let id = self
+            .streams2
+            .with_stream_by_id(stream_id, streams::helpers::get_stream_id());
 
         self.permissioner
             .borrow()
@@ -116,7 +117,8 @@ impl IggyShard {
             return Err(IggyError::StreamNameAlreadyExists(name.to_string()));
         }
 
-        self.streams2.with_stream_by_id_mut(id, streams::helpers::update_stream_name(name.clone()));
+        self.streams2
+            .with_stream_by_id_mut(id, streams::helpers::update_stream_name(name.clone()));
         self.streams2.with_index_mut(|index| {
             // Rename the key inside of hashmap
             let idx = index.remove(&old_name).expect("Rename key: key not found");
@@ -125,15 +127,11 @@ impl IggyShard {
         Ok(())
     }
 
-    pub fn delete_stream2_bypass_auth(
-        &self,
-        id: &Identifier,
-    ) -> Result<stream2::Stream, IggyError> {
-        let stream = self.delete_stream2_base(id)?;
-        Ok(stream)
+    pub fn delete_stream2_bypass_auth(&self, id: &Identifier) -> stream2::Stream {
+        self.delete_stream2_base(id)
     }
 
-    fn delete_stream2_base(&self, id: &Identifier) -> Result<stream2::Stream, IggyError> {
+    fn delete_stream2_base(&self, id: &Identifier) -> stream2::Stream {
         let id = self.streams2.get_index(id);
         let stream = self.streams2.delete(id);
         let stats = stream.stats();
@@ -151,7 +149,7 @@ impl IggyShard {
             .borrow_mut()
             .delete_consumer_groups_for_stream(stream_id as u32);
         */
-        Ok(stream)
+        stream
     }
 
     pub fn delete_stream2(
@@ -161,7 +159,9 @@ impl IggyShard {
     ) -> Result<stream2::Stream, IggyError> {
         self.ensure_authenticated(session)?;
         self.ensure_stream_exists(id)?;
-        let stream_id = self.streams2.with_stream_by_id(id, streams::helpers::get_stream_id());
+        let stream_id = self
+            .streams2
+            .with_stream_by_id(id, streams::helpers::get_stream_id());
         self.permissioner
             .borrow()
             .delete_stream(session.get_user_id(), stream_id as u32)
@@ -172,7 +172,7 @@ impl IggyShard {
                     stream_id,
                 )
             })?;
-        let stream = self.delete_stream2_base(id)?;
+        let stream = self.delete_stream2_base(id);
         Ok(stream)
     }
 
diff --git a/core/server/src/shard/system/topics.rs b/core/server/src/shard/system/topics.rs
index 4daf0545..417f4f62 100644
--- a/core/server/src/shard/system/topics.rs
+++ b/core/server/src/shard/system/topics.rs
@@ -18,18 +18,14 @@
 
 use super::COMPONENT;
 use crate::shard::IggyShard;
-use crate::shard::namespace::IggyNamespace;
 use crate::shard_info;
 use crate::slab::traits_ext::{EntityMarker, InsertCell};
 use crate::streaming::session::Session;
 use crate::streaming::stats::stats::{StreamStats, TopicStats};
-use crate::streaming::streams::stream::Stream;
 use crate::streaming::topics::storage2::create_topic_file_hierarchy;
-use crate::streaming::topics::topic::Topic;
 use crate::streaming::topics::topic2::{self, resolve_max_topic_size, resolve_message_expiry};
 use crate::streaming::{streams, topics};
 use error_set::ErrContext;
-use iggy_common::locking::IggyRwLockFn;
 use iggy_common::{
     CompressionAlgorithm, Identifier, IggyError, IggyExpiry, IggyTimestamp, MaxTopicSize,
 };
@@ -48,7 +44,7 @@ impl IggyShard {
         replication_factor: Option<u8>,
     ) -> Result<topic2::Topic, IggyError> {
         self.ensure_authenticated(session)?;
-        //self.ensure_stream_exists(stream_id)?;
+        self.ensure_stream_exists(stream_id)?;
         let numeric_stream_id = self.streams2.get_index(stream_id);
         {
             self.permissioner
@@ -127,13 +123,8 @@ impl IggyShard {
             .with_topics(stream_id, |topics| topics.insert(topic))
     }
 
-    pub fn create_topic2_bypass_auth(
-        &self,
-        stream_id: &Identifier,
-        topic: topic2::Topic,
-    ) -> Result<usize, IggyError> {
-        let topic_id = self.insert_topic_mem(stream_id, topic);
-        Ok(topic_id)
+    pub fn create_topic2_bypass_auth(&self, stream_id: &Identifier, topic: topic2::Topic) -> usize {
+        self.insert_topic_mem(stream_id, topic)
     }
 
     pub fn update_topic2(
@@ -259,9 +250,7 @@ impl IggyShard {
                     )
                 })?;
         }
-        let topic = self.delete_topic_base2(stream_id, topic_id).with_error_context(|error| {
-            format!("{COMPONENT} (error: {error}) - failed to delete topic with ID: {topic_id} in stream with ID: {stream_id}")
-        })?;
+        let topic = self.delete_topic_base2(stream_id, topic_id);
         // TODO: Decrease the stats
         Ok(topic)
     }
@@ -270,19 +259,17 @@ impl IggyShard {
         &self,
         stream_id: &Identifier,
         topic_id: &Identifier,
-    ) -> Result<topic2::Topic, IggyError> {
-        let topic = self.delete_topic_base2(stream_id, topic_id)?;
-        Ok(topic)
+    ) -> topic2::Topic {
+        self.delete_topic_base2(stream_id, topic_id)
     }
 
     pub fn delete_topic_base2(
         &self,
         stream_id: &Identifier,
         topic_id: &Identifier,
-    ) -> Result<topic2::Topic, IggyError> {
-        let delete_topic_closure = topics::helpers::delete_topic(topic_id);
-        let topic = self.streams2.with_topics(stream_id, delete_topic_closure);
-        Ok(topic)
+    ) -> topic2::Topic {
+        self.streams2
+            .with_topics(stream_id, topics::helpers::delete_topic(topic_id))
     }
 
     pub async fn purge_topic2(
diff --git a/core/server/src/shard/system/utils.rs b/core/server/src/shard/system/utils.rs
index ad23d984..3a11efcd 100644
--- a/core/server/src/shard/system/utils.rs
+++ b/core/server/src/shard/system/utils.rs
@@ -1,6 +1,9 @@
 use iggy_common::{Identifier, IggyError};
 
-use crate::shard::IggyShard; 
+use crate::{
+    shard::IggyShard,
+    streaming::topics::{self},
+};
 
 impl IggyShard {
     pub fn ensure_stream_exists(&self, stream_id: &Identifier) -> Result<(), IggyError> {
@@ -18,7 +21,7 @@ impl IggyShard {
         self.ensure_stream_exists(stream_id)?;
         let exists = self
             .streams2
-            .with_topics(stream_id, |topics| topics.exists(topic_id));
+            .with_topics(stream_id, topics::helpers::exists(topic_id));
         if !exists {
             return Err(IggyError::TopicIdNotFound(0, 0));
         }
@@ -31,13 +34,13 @@ impl IggyShard {
         topic_id: &Identifier,
         group_id: &Identifier,
     ) -> Result<(), IggyError> {
-        //self.ensure_stream_exists(stream_id)?;
-        //self.ensure_topic_exists(stream_id, topic_id)?;
-        let exists = self
-            .streams2
-            .with_topic_by_id(stream_id, topic_id, |(root, _)| {
-                root.consumer_groups().exists(group_id)
-            });
+        self.ensure_stream_exists(stream_id)?;
+        self.ensure_topic_exists(stream_id, topic_id)?;
+        let exists = self.streams2.with_topic_by_id(
+            stream_id,
+            topic_id,
+            topics::helpers::cg_exists(group_id),
+        );
         if !exists {
             return Err(IggyError::ConsumerGroupIdNotFound(0, 0));
         }
diff --git a/core/server/src/slab/consumer_groups.rs b/core/server/src/slab/consumer_groups.rs
index c52fda6d..7ad2c20c 100644
--- a/core/server/src/slab/consumer_groups.rs
+++ b/core/server/src/slab/consumer_groups.rs
@@ -1,42 +1,110 @@
-use crate::{slab::Keyed, streaming::topics::consumer_group2};
+use crate::{
+    slab::{
+        Keyed, consumer_groups,
+        traits_ext::{
+            Borrow, ComponentsById, Delete, EntityComponentSystem, EntityComponentSystemMut,
+            Insert, IntoComponents, IntoComponentsById,
+        },
+    },
+    streaming::topics::consumer_group2::{self, ConsumerGroupRef, ConsumerGroupRefMut},
+};
 use ahash::AHashMap;
-use arcshift::ArcShift;
 use iggy_common::Identifier;
 use slab::Slab;
-use std::sync::{Arc, atomic::AtomicUsize};
 
 const CAPACITY: usize = 1024;
+pub type ContainerId = usize;
 
 #[derive(Debug, Clone)]
 pub struct ConsumerGroups {
-    index: AHashMap<<consumer_group2::ConsumerGroup as Keyed>::Key, usize>,
-    container: Slab<consumer_group2::ConsumerGroup>,
+    index: AHashMap<<consumer_group2::ConsumerGroupRoot as Keyed>::Key, usize>,
+    members: Slab<consumer_group2::ConsumerGroupMembers>,
+    root: Slab<consumer_group2::ConsumerGroupRoot>,
 }
 
-impl ConsumerGroups {
-    pub fn with<T>(&self, f: impl FnOnce(&Slab<consumer_group2::ConsumerGroup>) -> T) -> T {
-        f(&self.container)
+impl Insert for ConsumerGroups {
+    type Idx = consumer_groups::ContainerId;
+    type Item = consumer_group2::ConsumerGroup;
+
+    fn insert(&mut self, item: Self::Item) -> Self::Idx {
+        let (root, members) = item.into_components();
+        let key = root.key().clone();
+
+        let entity_id = self.root.insert(root);
+        let id = self.members.insert(members);
+        assert_eq!(
+            entity_id, id,
+            "consumer_group: id mismatch when inserting members"
+        );
+        self.index.insert(key, entity_id);
+        entity_id
     }
+}
 
-    pub fn with_mut<T>(
-        &mut self,
-        f: impl FnOnce(&mut Slab<consumer_group2::ConsumerGroup>) -> T,
-    ) -> T {
-        f(&mut self.container)
+impl Delete for ConsumerGroups {
+    type Idx = consumer_groups::ContainerId;
+    type Item = consumer_group2::ConsumerGroup;
+
+    fn delete(&mut self, id: Self::Idx) -> Self::Item {
+        let (name, partitions) = self.root.remove(id).disarray();
+        let members = self.members.remove(id).into_inner();
+        self.index
+            .remove(&name)
+            .expect("consumer_group_delete: key not found");
+        consumer_group2::ConsumerGroup::new(name, members, partitions)
     }
+}
 
-    pub fn with_index<T>(
-        &self,
-        f: impl FnOnce(&AHashMap<<consumer_group2::ConsumerGroup as Keyed>::Key, usize>) -> T,
-    ) -> T {
-        f(&self.index)
+//TODO: those from impls could use a macro aswell.
+impl<'a> From<&'a ConsumerGroups> for consumer_group2::ConsumerGroupRef<'a> {
+    fn from(value: &'a ConsumerGroups) -> Self {
+        consumer_group2::ConsumerGroupRef::new(&value.root, &value.members)
+    }
+}
+
+impl<'a> From<&'a mut ConsumerGroups> for consumer_group2::ConsumerGroupRefMut<'a> {
+    fn from(value: &'a mut ConsumerGroups) -> Self {
+        consumer_group2::ConsumerGroupRefMut::new(&mut value.root, &mut value.members)
+    }
+}
+
+impl EntityComponentSystem<Borrow> for ConsumerGroups {
+    type Idx = consumer_groups::ContainerId;
+    type Entity = consumer_group2::ConsumerGroup;
+    type EntityComponents<'a> = consumer_group2::ConsumerGroupRef<'a>;
+
+    fn with_components<O, F>(&self, f: F) -> O
+    where
+        F: for<'a> FnOnce(Self::EntityComponents<'a>) -> O,
+    {
+        f(self.into())
     }
 
+    fn with_components_async<O, F>(&self, f: F) -> impl Future<Output = O>
+    where
+        F: for<'a> AsyncFnOnce(Self::EntityComponents<'a>) -> O,
+    {
+        f(self.into())
+    }
+}
+
+impl EntityComponentSystemMut for ConsumerGroups {
+    type EntityComponentsMut<'a> = consumer_group2::ConsumerGroupRefMut<'a>;
+
+    fn with_components_mut<O, F>(&mut self, f: F) -> O
+    where
+        F: for<'a> FnOnce(Self::EntityComponentsMut<'a>) -> O,
+    {
+        f(self.into())
+    }
+}
+
+impl ConsumerGroups {
     pub fn exists(&self, id: &Identifier) -> bool {
         match id.kind {
             iggy_common::IdKind::Numeric => {
                 let id = id.get_u32_value().unwrap() as usize;
-                self.container.contains(id)
+                self.root.contains(id)
             }
             iggy_common::IdKind::String => {
                 let key = id.get_string_value().unwrap();
@@ -44,13 +112,53 @@ impl ConsumerGroups {
             }
         }
     }
+
+    pub fn get_index(&self, id: &Identifier) -> usize {
+        match id.kind {
+            iggy_common::IdKind::Numeric => id.get_u32_value().unwrap() as usize,
+            iggy_common::IdKind::String => {
+                let key = id.get_string_value().unwrap();
+                *self.index.get(&key).expect("Consumer Group not found")
+            }
+        }
+    }
+
+    pub fn with_consumer_group_by_id<T>(
+        &self,
+        identifier: &Identifier,
+        f: impl FnOnce(ComponentsById<ConsumerGroupRef>) -> T,
+    ) -> T {
+        let id = self.get_index(identifier);
+        self.with_components(|components| f(components.into_components_by_id(id)))
+    }
+
+    pub fn with_consumer_group_by_id_mut<T>(
+        &mut self,
+        identifier: &Identifier,
+        f: impl FnOnce(ComponentsById<ConsumerGroupRefMut>) -> T,
+    ) -> T {
+        let id = self.get_index(identifier);
+        self.with_components_mut(|components| f(components.into_components_by_id(id)))
+    }
+
+    pub fn with_consumer_group_by_id_async<T>(
+        &self,
+        identifier: &Identifier,
+        f: impl AsyncFnOnce(ComponentsById<ConsumerGroupRef>) -> T,
+    ) -> impl Future<Output = T> {
+        let id = self.get_index(identifier);
+        self.with_components_async(async move |components| {
+            f(components.into_components_by_id(id)).await
+        })
+    }
 }
 
 impl Default for ConsumerGroups {
     fn default() -> Self {
         Self {
             index: AHashMap::with_capacity(CAPACITY),
-            container: Slab::with_capacity(CAPACITY),
+            root: Slab::with_capacity(CAPACITY),
+            members: Slab::with_capacity(CAPACITY),
         }
     }
 }
diff --git a/core/server/src/slab/helpers.rs b/core/server/src/slab/helpers.rs
index 20d36014..5628abce 100644
--- a/core/server/src/slab/helpers.rs
+++ b/core/server/src/slab/helpers.rs
@@ -1,8 +1,14 @@
 use crate::{
-    slab::{partitions::Partitions, topics::Topics, traits_ext::ComponentsById},
+    slab::{
+        consumer_groups::ConsumerGroups, partitions::Partitions, topics::Topics,
+        traits_ext::ComponentsById,
+    },
     streaming::{
         streams::stream2::{StreamRef, StreamRefMut},
-        topics::topic2::{TopicRef, TopicRefMut},
+        topics::{
+            consumer_group2::ConsumerGroupRef,
+            topic2::{TopicRef, TopicRefMut},
+        },
     },
 };
 
@@ -14,7 +20,7 @@ where
     |(root, _)| f(root.topics())
 }
 
-pub async fn topics_async<O, F>(f: F) -> impl AsyncFnOnce(ComponentsById<StreamRef>) -> O
+pub fn topics_async<O, F>(f: F) -> impl AsyncFnOnce(ComponentsById<StreamRef>) -> O
 where
     F: for<'a> AsyncFnOnce(&'a Topics) -> O,
 {
@@ -35,7 +41,7 @@ where
     |(root, _)| f(root.partitions())
 }
 
-pub async fn partitions_async<O, F>(f: F) -> impl AsyncFnOnce(ComponentsById<TopicRef>) -> O
+pub fn partitions_async<O, F>(f: F) -> impl AsyncFnOnce(ComponentsById<TopicRef>) -> O
 where
     F: for<'a> AsyncFnOnce(&'a Partitions) -> O,
 {
@@ -48,3 +54,24 @@ where
 {
     |(mut root, _)| f(root.partitions_mut())
 }
+
+pub fn consumer_groups<O, F>(f: F) -> impl FnOnce(ComponentsById<TopicRef>) -> O
+where
+    F: for<'a> FnOnce(&'a ConsumerGroups) -> O,
+{
+    |(root, _)| f(root.consumer_groups())
+}
+
+pub fn consumer_groups_mut<O, F>(f: F) -> impl FnOnce(ComponentsById<TopicRefMut>) -> O
+where
+    F: for<'a> FnOnce(&'a mut ConsumerGroups) -> O,
+{
+    |(mut root, _)| f(root.consumer_groups_mut())
+}
+
+pub fn consumer_groups_async<O, F>(f: F) -> impl AsyncFnOnce(ComponentsById<TopicRef>) -> O
+where
+    F: for<'a> AsyncFnOnce(&'a ConsumerGroups) -> O,
+{
+    async |(root, _)| f(root.consumer_groups()).await
+}
diff --git a/core/server/src/slab/partitions.rs b/core/server/src/slab/partitions.rs
index eed18c12..ac005c0d 100644
--- a/core/server/src/slab/partitions.rs
+++ b/core/server/src/slab/partitions.rs
@@ -109,11 +109,11 @@ impl EntityComponentSystem<Borrow> for Partitions {
         f(self.into())
     }
 
-    async fn with_components_async<O, F>(&self, f: F) -> O
+    fn with_components_async<O, F>(&self, f: F) -> impl Future<Output = O>
     where
         F: for<'a> AsyncFnOnce(Self::EntityComponents<'a>) -> O,
     {
-        f(self.into()).await
+        f(self.into())
     }
 }
 
diff --git a/core/server/src/slab/streams.rs b/core/server/src/slab/streams.rs
index 7f93667a..1044bbec 100644
--- a/core/server/src/slab/streams.rs
+++ b/core/server/src/slab/streams.rs
@@ -1,18 +1,23 @@
 use crate::{
     slab::{
-        Keyed, helpers,
+        Keyed,
+        consumer_groups::ConsumerGroups,
+        helpers,
         partitions::Partitions,
         topics::Topics,
         traits_ext::{
-            Components, ComponentsById, ComponentsByIdMapping, ComponentsMapping, DeleteCell,
+            ComponentsById, ComponentsByIdMapping, ComponentsMapping, DeleteCell,
             EntityComponentSystem, EntityComponentSystemMutCell, InsertCell, InteriorMutability,
-            IntoComponents, IntoComponentsById,
+            IntoComponents,
         },
     },
     streaming::{
         stats::stats::StreamStats,
         streams::stream2::{self, StreamRef, StreamRefMut},
-        topics::topic2::{self, TopicRef, TopicRefMut},
+        topics::{
+            consumer_group2::{ConsumerGroupRef, ConsumerGroupRefMut},
+            topic2::{self, TopicRef, TopicRefMut},
+        },
     },
 };
 use ahash::AHashMap;
@@ -85,11 +90,11 @@ impl EntityComponentSystem<InteriorMutability> for Streams {
         f(self.into())
     }
 
-    async fn with_components_async<O, F>(&self, f: F) -> O
+    fn with_components_async<O, F>(&self, f: F) -> impl Future<Output = O>
     where
         F: for<'a> AsyncFnOnce(Self::EntityComponents<'a>) -> O,
     {
-        f(self.into()).await
+        f(self.into())
     }
 }
 
@@ -161,14 +166,13 @@ impl Streams {
         self.with_components_by_id(id, |stream| f(stream))
     }
 
-    pub async fn with_stream_by_id_async<T>(
+    pub fn with_stream_by_id_async<T>(
         &self,
         id: &Identifier,
         f: impl AsyncFnOnce(ComponentsById<StreamRef>) -> T,
-    ) -> T {
+    ) -> impl Future<Output = T> {
         let id = self.get_index(id);
         self.with_components_by_id_async(id, async |stream| f(stream).await)
-            .await
     }
 
     pub fn with_stream_by_id_mut<T>(
@@ -184,13 +188,12 @@ impl Streams {
         self.with_stream_by_id(stream_id, helpers::topics(f))
     }
 
-    pub async fn with_topics_async<T>(
+    pub fn with_topics_async<T>(
         &self,
         stream_id: &Identifier,
         f: impl AsyncFnOnce(&Topics) -> T,
-    ) -> T {
-        self.with_stream_by_id_async(stream_id, helpers::topics_async(f).await)
-            .await
+    ) -> impl Future<Output = T> {
+        self.with_stream_by_id_async(stream_id, helpers::topics_async(f))
     }
 
     pub fn with_topics_mut<T>(
@@ -212,16 +215,15 @@ impl Streams {
         })
     }
 
-    pub async fn with_topic_by_id_async<T>(
+    pub fn with_topic_by_id_async<T>(
         &self,
         stream_id: &Identifier,
         topic_id: &Identifier,
         f: impl AsyncFnOnce(ComponentsById<TopicRef>) -> T,
-    ) -> T {
+    ) -> impl Future<Output = T> {
         self.with_topics_async(stream_id, async |container| {
             container.with_topic_by_id_async(topic_id, f).await
         })
-        .await
     }
 
     pub fn with_topic_by_id_mut<T>(
@@ -235,6 +237,75 @@ impl Streams {
         })
     }
 
+    pub fn with_consumer_groups<T>(
+        &self,
+        stream_id: &Identifier,
+        topic_id: &Identifier,
+        f: impl FnOnce(&ConsumerGroups) -> T,
+    ) -> T {
+        self.with_topics(stream_id, |container| {
+            container.with_consumer_groups(topic_id, f)
+        })
+    }
+
+    pub fn with_consumer_groups_async<T>(
+        &self,
+        stream_id: &Identifier,
+        topic_id: &Identifier,
+        f: impl AsyncFnOnce(&ConsumerGroups) -> T,
+    ) -> impl Future<Output = T> {
+        self.with_topics_async(stream_id, async |container| {
+            container.with_consumer_groups_async(topic_id, f).await
+        })
+    }
+
+    pub fn with_consumer_group_by_id<T>(
+        &self,
+        stream_id: &Identifier,
+        topic_id: &Identifier,
+        group_id: &Identifier,
+        f: impl FnOnce(ComponentsById<ConsumerGroupRef>) -> T,
+    ) -> T {
+        self.with_consumer_groups(stream_id, topic_id, |container| {
+            container.with_consumer_group_by_id(group_id, f)
+        })
+    }
+
+    pub fn with_consumer_group_by_id_mut<T>(
+        &self,
+        stream_id: &Identifier,
+        topic_id: &Identifier,
+        group_id: &Identifier,
+        f: impl FnOnce(ComponentsById<ConsumerGroupRefMut>) -> T,
+    ) -> T {
+        self.with_consumer_groups_mut(stream_id, topic_id, |container| {
+            container.with_consumer_group_by_id_mut(group_id, f)
+        })
+    }
+
+    pub fn with_consumer_group_by_id_async<T>(
+        &self,
+        stream_id: &Identifier,
+        topic_id: &Identifier,
+        group_id: &Identifier,
+        f: impl AsyncFnOnce(ComponentsById<ConsumerGroupRef>) -> T,
+    ) -> impl Future<Output = T> {
+        self.with_consumer_groups_async(stream_id, topic_id, async move |container| {
+            container.with_consumer_group_by_id_async(group_id, f).await
+        })
+    }
+
+    pub fn with_consumer_groups_mut<T>(
+        &self,
+        stream_id: &Identifier,
+        topic_id: &Identifier,
+        f: impl FnOnce(&mut ConsumerGroups) -> T,
+    ) -> T {
+        self.with_topics_mut(stream_id, |container| {
+            container.with_consumer_groups_mut(topic_id, f)
+        })
+    }
+
     pub fn with_partitions<T>(
         &self,
         stream_id: &Identifier,
@@ -246,16 +317,15 @@ impl Streams {
         })
     }
 
-    pub async fn with_partitions_async<T>(
+    pub fn with_partitions_async<T>(
         &self,
         stream_id: &Identifier,
         topic_id: &Identifier,
         f: impl AsyncFnOnce(&Partitions) -> T,
-    ) -> T {
+    ) -> impl Future<Output = T> {
         self.with_topics_async(stream_id, async |container| {
             container.with_partitions_async(topic_id, f).await
         })
-        .await
     }
 
     pub fn with_partitions_mut<T>(
diff --git a/core/server/src/slab/topics.rs b/core/server/src/slab/topics.rs
index eb5af5ba..565efafc 100644
--- a/core/server/src/slab/topics.rs
+++ b/core/server/src/slab/topics.rs
@@ -5,17 +5,22 @@ use std::{cell::RefCell, sync::Arc};
 
 use crate::{
     slab::{
-        Keyed, helpers,
+        Keyed,
+        consumer_groups::ConsumerGroups,
+        helpers,
         partitions::Partitions,
         traits_ext::{
-            ComponentsById, Delete, DeleteCell, EntityComponentSystem,
+            Components, ComponentsById, Delete, DeleteCell, EntityComponentSystem,
             EntityComponentSystemMutCell, Insert, InsertCell, InteriorMutability, IntoComponents,
         },
     },
     streaming::{
-        partitions::partition2,
+        partitions::partition2::{self, PartitionRef},
         stats::stats::TopicStats,
-        topics::topic2::{self, TopicRef, TopicRefMut},
+        topics::{
+            consumer_group2::{ConsumerGroupRef, ConsumerGroupRefMut},
+            topic2::{self, TopicRef, TopicRefMut},
+        },
     },
 };
 
@@ -53,6 +58,7 @@ impl DeleteCell for Topics {
     type Item = topic2::Topic;
 
     fn delete(&self, id: Self::Idx) -> Self::Item {
+        // TODO: don't forget to remoev from the index
         todo!()
     }
 }
@@ -65,6 +71,15 @@ impl<'a> From<&'a Topics> for topic2::TopicRef<'a> {
         topic2::TopicRef::new(root, stats)
     }
 }
+
+impl<'a> From<&'a Topics> for topic2::TopicRefMut<'a> {
+    fn from(value: &'a Topics) -> Self {
+        let root = value.root.borrow_mut();
+        let stats = value.stats.borrow_mut();
+        topic2::TopicRefMut::new(root, stats)
+    }
+}
+
 impl Default for Topics {
     fn default() -> Self {
         Self {
@@ -75,14 +90,6 @@ impl Default for Topics {
     }
 }
 
-impl<'a> From<&'a Topics> for topic2::TopicRefMut<'a> {
-    fn from(value: &'a Topics) -> Self {
-        let root = value.root.borrow_mut();
-        let stats = value.stats.borrow_mut();
-        topic2::TopicRefMut::new(root, stats)
-    }
-}
-
 impl EntityComponentSystem<InteriorMutability> for Topics {
     type Idx = ContainerId;
     type Entity = topic2::Topic;
@@ -95,11 +102,11 @@ impl EntityComponentSystem<InteriorMutability> for Topics {
         f(self.into())
     }
 
-    async fn with_components_async<O, F>(&self, f: F) -> O
+    fn with_components_async<O, F>(&self, f: F) -> impl Future<Output = O>
     where
         F: for<'a> AsyncFnOnce(Self::EntityComponents<'a>) -> O,
     {
-        f(self.into()).await
+        f(self.into())
     }
 }
 
@@ -167,14 +174,13 @@ impl Topics {
         self.with_components_by_id(id, |components| f(components))
     }
 
-    pub async fn with_topic_by_id_async<T>(
+    pub fn with_topic_by_id_async<T>(
         &self,
         topic_id: &Identifier,
         f: impl AsyncFnOnce(ComponentsById<TopicRef>) -> T,
-    ) -> T {
+    ) -> impl Future<Output = T> {
         let id = self.get_index(topic_id);
         self.with_components_by_id_async(id, async |components| f(components).await)
-            .await
     }
 
     pub fn with_topic_by_id_mut<T>(
@@ -186,17 +192,73 @@ impl Topics {
         self.with_components_by_id_mut(id, |components| f(components))
     }
 
+    pub fn with_consumer_groups<T>(
+        &self,
+        topic_id: &Identifier,
+        f: impl FnOnce(&ConsumerGroups) -> T,
+    ) -> T {
+        self.with_topic_by_id(topic_id, helpers::consumer_groups(f))
+    }
+
+    pub fn with_consumer_groups_async<T>(
+        &self,
+        topic_id: &Identifier,
+        f: impl AsyncFnOnce(&ConsumerGroups) -> T,
+    ) -> impl Future<Output = T> {
+        self.with_topic_by_id_async(topic_id, helpers::consumer_groups_async(f))
+    }
+
+    pub fn with_consumer_groups_mut<T>(
+        &self,
+        topic_id: &Identifier,
+        f: impl FnOnce(&mut ConsumerGroups) -> T,
+    ) -> T {
+        self.with_topic_by_id_mut(topic_id, helpers::consumer_groups_mut(f))
+    }
+
+    pub fn with_consumer_group_by_id<T>(
+        &self,
+        topic_id: &Identifier,
+        group_id: &Identifier,
+        f: impl FnOnce(ComponentsById<ConsumerGroupRef>) -> T,
+    ) -> T {
+        self.with_consumer_groups(topic_id, |container| {
+            container.with_consumer_group_by_id(group_id, f)
+        })
+    }
+
+    pub fn with_consumer_group_by_id_async<T>(
+        &self,
+        topic_id: &Identifier,
+        group_id: &Identifier,
+        f: impl AsyncFnOnce(ComponentsById<ConsumerGroupRef>) -> T,
+    ) -> impl Future<Output = T> {
+        self.with_consumer_groups_async(topic_id, async |container| {
+            container.with_consumer_group_by_id_async(group_id, f).await
+        })
+    }
+
+    pub fn with_consumer_group_by_id_mut<T>(
+        &self,
+        topic_id: &Identifier,
+        group_id: &Identifier,
+        f: impl FnOnce(ComponentsById<ConsumerGroupRefMut>) -> T,
+    ) -> T {
+        self.with_consumer_groups_mut(topic_id, |container| {
+            container.with_consumer_group_by_id_mut(group_id, f)
+        })
+    }
+
     pub fn with_partitions<T>(&self, topic_id: &Identifier, f: impl FnOnce(&Partitions) -> T) -> T {
         self.with_topic_by_id(topic_id, helpers::partitions(f))
     }
 
-    pub async fn with_partitions_async<T>(
+    pub fn with_partitions_async<T>(
         &self,
         topic_id: &Identifier,
         f: impl AsyncFnOnce(&Partitions) -> T,
-    ) -> T {
-        self.with_topic_by_id_async(topic_id, helpers::partitions_async(f).await)
-            .await
+    ) -> impl Future<Output = T> {
+        self.with_topic_by_id_async(topic_id, helpers::partitions_async(f))
     }
 
     pub fn with_partitions_mut<T>(
diff --git a/core/server/src/slab/traits_ext.rs b/core/server/src/slab/traits_ext.rs
index ac33243e..fe7a65c8 100644
--- a/core/server/src/slab/traits_ext.rs
+++ b/core/server/src/slab/traits_ext.rs
@@ -166,6 +166,9 @@ pub type ComponentsById<'a, T> = <T as IntoComponentsById>::Output;
 // This way we can name the type inside of the `with_by_id` methods, without desolving into the tuple mapping madness.
 // in the `stream.rs` `topic.rs` `partitions.rs` files, we need to implement the `IntoComponentsById` trait for the output type of `IntoComponents` implementation, for `EntityRef`.
 // to make our life easier, we can create a type alias for those tuples and maybe even create a macro, to not repeat the type 3 times per entity (TupleEntityType, TupleEntityTypeRef, TupleEntityTypeRefByid).
+
+// TODO: Since those traits at impl site all they do is call `f(self.into())`
+// we can blanket implement those for all types that implement `From` trait.
 pub trait EntityComponentSystem<T>
 where
     <Self::Entity as IntoComponents>::Components: ComponentsMapping<T> + ComponentsByIdMapping<T>,
diff --git a/core/server/src/streaming/partitions/helpers.rs b/core/server/src/streaming/partitions/helpers.rs
new file mode 100644
index 00000000..0e8fb618
--- /dev/null
+++ b/core/server/src/streaming/partitions/helpers.rs
@@ -0,0 +1,18 @@
+use crate::{
+    slab::{
+        partitions::Partitions,
+        traits_ext::{Components, EntityComponentSystem, IntoComponents},
+    },
+    streaming::partitions::partition2::PartitionRef,
+};
+
+pub fn get_partition_ids() -> impl FnOnce(&Partitions) -> Vec<usize> {
+    |partitions| {
+        partitions.with_components(|components| {
+            let (root, ..) = components.into_components();
+            root.iter()
+                .map(|(_, partition)| partition.id())
+                .collect::<Vec<_>>()
+        })
+    }
+}
diff --git a/core/server/src/streaming/partitions/mod.rs b/core/server/src/streaming/partitions/mod.rs
index 08e8eaae..37fbc6e4 100644
--- a/core/server/src/streaming/partitions/mod.rs
+++ b/core/server/src/streaming/partitions/mod.rs
@@ -18,6 +18,7 @@
 
 pub mod consumer_offset;
 pub mod consumer_offsets;
+pub mod helpers;
 pub mod messages;
 pub mod partition;
 pub mod partition2;
diff --git a/core/server/src/streaming/topics/consumer_group2.rs b/core/server/src/streaming/topics/consumer_group2.rs
index d3785052..e48fe981 100644
--- a/core/server/src/streaming/topics/consumer_group2.rs
+++ b/core/server/src/streaming/topics/consumer_group2.rs
@@ -1,60 +1,183 @@
-use crate::{
-    binary::handlers::partitions,
-    slab::{Keyed, partitions::PARTITIONS_CAPACITY},
+use crate::slab::{
+    Keyed, consumer_groups, partitions,
+    traits_ext::{EntityMarker, IntoComponents, IntoComponentsById},
 };
-use ahash::AHashMap;
 use arcshift::ArcShift;
-use iggy_common::IggyError;
 use slab::Slab;
-use std::{
-    sync::{
-        Arc,
-        atomic::{AtomicUsize, Ordering},
-    },
-    task::Context,
-};
+use std::sync::atomic::{AtomicUsize, Ordering};
 use tracing::trace;
 
 pub const MEMBERS_CAPACITY: usize = 128;
 
-#[derive(Default, Debug, Clone)]
+#[derive(Debug, Clone)]
+pub struct ConsumerGroupMembers {
+    inner: ArcShift<Slab<Member>>,
+}
+
+impl ConsumerGroupMembers {
+    pub fn new(inner: ArcShift<Slab<Member>>) -> Self {
+        Self { inner }
+    }
+
+    pub fn into_inner(self) -> ArcShift<Slab<Member>> {
+        self.inner
+    }
+
+    pub fn inner(&self) -> &ArcShift<Slab<Member>> {
+        &self.inner
+    }
+
+    pub fn inner_mut(&mut self) -> &mut ArcShift<Slab<Member>> {
+        &mut self.inner
+    }
+}
+
+#[derive(Debug, Clone)]
 pub struct ConsumerGroup {
+    root: ConsumerGroupRoot,
+    members: ConsumerGroupMembers,
+}
+
+#[derive(Default, Debug, Clone)]
+pub struct ConsumerGroupRoot {
     id: usize,
     name: String,
-    partitions: Vec<usize>,
-    members: ArcShift<Slab<Member>>,
+    partitions: Vec<partitions::ContainerId>,
 }
 
-impl ConsumerGroup {
-    pub fn new(name: String, members: ArcShift<Slab<Member>>, partitions: Vec<usize>) -> Self {
-        ConsumerGroup {
-            id: 0,
-            name,
-            partitions,
-            members,
-        }
+impl ConsumerGroupRoot {
+    pub fn disarray(self) -> (String, Vec<usize>) {
+        (self.name, self.partitions)
     }
 
-    pub fn id(&self) -> usize {
+    pub fn partitions(&self) -> &Vec<partitions::ContainerId> {
+        &self.partitions
+    }
+
+    pub fn partitions_mut(&mut self) -> &mut Vec<partitions::ContainerId> {
+        &mut self.partitions
+    }
+
+    pub fn id(&self) -> consumer_groups::ContainerId {
         self.id
     }
+}
 
-    pub fn insert_into(self, container: &mut Slab<Self>) -> usize {
-        let idx = container.insert(self);
-        let group = &mut container[idx];
-        group.id = idx;
-        idx
+impl Keyed for ConsumerGroupRoot {
+    type Key = String;
+
+    fn key(&self) -> &Self::Key {
+        &self.name
+    }
+}
+
+impl EntityMarker for ConsumerGroup {
+    type Idx = consumer_groups::ContainerId;
+
+    fn id(&self) -> Self::Idx {
+        self.root.id
     }
 
-    pub fn with_members<T>(&self, f: impl FnOnce(&Slab<Member>) -> T) -> T {
-        f(&self.members.shared_get())
+    fn update_id(&mut self, id: Self::Idx) {
+        self.root.id = id;
     }
+}
 
-    pub fn reassign_partitions(&mut self, partitions: Vec<usize>) {
-        self.partitions = partitions;
+impl IntoComponents for ConsumerGroup {
+    type Components = (ConsumerGroupRoot, ConsumerGroupMembers);
+
+    fn into_components(self) -> Self::Components {
+        (self.root, self.members)
+    }
+}
+
+// TODO: Create a macro to impl those ConsumerGroupRef/ConsumerGroupRefMut structs and it's traits.
+pub struct ConsumerGroupRef<'a> {
+    root: &'a Slab<ConsumerGroupRoot>,
+    members: &'a Slab<ConsumerGroupMembers>,
+}
+
+impl<'a> ConsumerGroupRef<'a> {
+    pub fn new(root: &'a Slab<ConsumerGroupRoot>, members: &'a Slab<ConsumerGroupMembers>) -> Self {
+        Self { root, members }
+    }
+}
+
+impl<'a> IntoComponents for ConsumerGroupRef<'a> {
+    type Components = (&'a Slab<ConsumerGroupRoot>, &'a Slab<ConsumerGroupMembers>);
+
+    fn into_components(self) -> Self::Components {
+        (self.root, self.members)
+    }
+}
+
+impl<'a> IntoComponentsById for ConsumerGroupRef<'a> {
+    type Idx = consumer_groups::ContainerId;
+    type Output = (&'a ConsumerGroupRoot, &'a ConsumerGroupMembers);
+
+    fn into_components_by_id(self, index: Self::Idx) -> Self::Output {
+        let root = &self.root[index];
+        let members = &self.members[index];
+        (root, members)
+    }
+}
+
+pub struct ConsumerGroupRefMut<'a> {
+    root: &'a mut Slab<ConsumerGroupRoot>,
+    members: &'a mut Slab<ConsumerGroupMembers>,
+}
+
+impl<'a> ConsumerGroupRefMut<'a> {
+    pub fn new(
+        root: &'a mut Slab<ConsumerGroupRoot>,
+        members: &'a mut Slab<ConsumerGroupMembers>,
+    ) -> Self {
+        Self { root, members }
+    }
+}
+
+impl<'a> IntoComponents for ConsumerGroupRefMut<'a> {
+    type Components = (
+        &'a mut Slab<ConsumerGroupRoot>,
+        &'a mut Slab<ConsumerGroupMembers>,
+    );
+
+    fn into_components(self) -> Self::Components {
+        (self.root, self.members)
+    }
+}
+
+impl<'a> IntoComponentsById for ConsumerGroupRefMut<'a> {
+    type Idx = consumer_groups::ContainerId;
+    type Output = (&'a mut ConsumerGroupRoot, &'a mut ConsumerGroupMembers);
+
+    fn into_components_by_id(self, index: Self::Idx) -> Self::Output {
+        let root = &mut self.root[index];
+        let members = &mut self.members[index];
+        (root, members)
+    }
+}
+
+impl ConsumerGroup {
+    pub fn new(
+        name: String,
+        members: ArcShift<Slab<Member>>,
+        partitions: Vec<partitions::ContainerId>,
+    ) -> Self {
+        let root = ConsumerGroupRoot {
+            id: 0,
+            name,
+            partitions,
+        };
+        let members = ConsumerGroupMembers { inner: members };
+        Self { root, members }
+    }
+
+    pub fn reassign_partitions(&mut self, partitions: Vec<partitions::ContainerId>) {
+        self.root.partitions = partitions;
         self.members.rcu(|members| {
             let mut members = Self::mimic_members(members);
-            let partitions = self.partitions.clone();
+            let partitions = self.root.partitions.clone();
             Self::assign_partitions_to_members(self.id, &mut members, partitions);
             members
         });
@@ -92,68 +215,14 @@ impl ConsumerGroup {
             Some(member.partitions[partition_idx])
         })
     }
-
-    pub fn add_member(&mut self, client_id: u32) {
-        self.members.rcu(|members| {
-            let mut members = Self::mimic_members(members);
-            Member::new(client_id).insert_into(&mut members);
-            let partitions = self.partitions.clone();
-            Self::assign_partitions_to_members(self.id, &mut members, partitions);
-            members
-        });
-    }
-
-    pub fn delete_member(&mut self, client_id: u32) {
-        let member_id = self
-            .members
-            .shared_get()
-            .iter()
-            .find_map(|(_, member)| (member.client_id == client_id).then_some(member.id))
-            .expect("delete_member: find member in consumer group slab");
-        self.members.rcu(|members| {
-            let mut members = Self::mimic_members(members);
-            let partitions = self.partitions.clone();
-            members.remove(member_id);
-            members.compact(|entry, _, idx| {
-                entry.id = idx;
-                true
-            });
-            Self::assign_partitions_to_members(self.id, &mut members, partitions);
-            members
-        });
-    }
-
-    fn mimic_members(members: &Slab<Member>) -> Slab<Member> {
-        let mut container = Slab::with_capacity(members.len());
-        for (_, member) in members {
-            Member::new(member.client_id).insert_into(&mut container);
-        }
-        container
-    }
-
-    fn assign_partitions_to_members(id: usize, members: &mut Slab<Member>, partitions: Vec<usize>) {
-        members
-            .iter_mut()
-            .for_each(|(_, member)| member.partitions.clear());
-        let count = members.len();
-        for (idx, partition) in partitions.iter().enumerate() {
-            let position = idx % count;
-            let member = &mut members[position];
-            member.partitions.push(*partition);
-            trace!(
-                "Assigned partition ID: {} to member with ID: {} in consumer group: {}",
-                partition, member.id, id
-            );
-        }
-    }
 }
 
 #[derive(Debug)]
 pub struct Member {
-    id: usize,
-    client_id: u32,
-    partitions: Vec<usize>,
-    current_partition_idx: AtomicUsize,
+    pub id: usize,
+    pub client_id: u32,
+    pub partitions: Vec<partitions::ContainerId>,
+    pub current_partition_idx: AtomicUsize,
 }
 
 impl Clone for Member {
@@ -193,14 +262,6 @@ impl Member {
     }
 }
 
-impl Keyed for ConsumerGroup {
-    type Key = String;
-
-    fn key(&self) -> &Self::Key {
-        &self.name
-    }
-}
-
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -227,8 +288,8 @@ mod tests {
     fn test_initial_creation_with_few_members(members_count: usize) {
         let consumer_group = create_test_consumer_group("test_group", members_count);
 
-        assert_eq!(consumer_group.name, "test_group");
-        assert_eq!(consumer_group.id, 0); // Initial ID should be 0
+        assert_eq!(consumer_group.root.name, "test_group");
+        assert_eq!(consumer_group.root.id, 0); // Initial ID should be 0
 
         consumer_group.with_members(|members| {
             assert_eq!(members.len(), members_count);
diff --git a/core/server/src/streaming/topics/helpers.rs b/core/server/src/streaming/topics/helpers.rs
index 6986c493..c0f0bb19 100644
--- a/core/server/src/streaming/topics/helpers.rs
+++ b/core/server/src/streaming/topics/helpers.rs
@@ -1,12 +1,33 @@
+use std::sync::{atomic::Ordering, Arc};
+
 use crate::{
+    shard_trace,
     slab::{
         Keyed,
+        consumer_groups::{self, ConsumerGroups},
+        partitions,
         topics::{self, Topics},
-        traits_ext::{ComponentsById, DeleteCell, EntityMarker},
+        traits_ext::{
+            ComponentsById, Delete, DeleteCell, EntityComponentSystem, EntityComponentSystemMut,
+            EntityMarker, Insert, IntoComponents,
+        },
+    },
+    streaming::{
+        partitions::partition2,
+        stats::stats::TopicStats,
+        topics::{
+            consumer_group2::{
+                self, ConsumerGroupMembers, ConsumerGroupRef, ConsumerGroupRefMut,
+                MEMBERS_CAPACITY, Member,
+            },
+            topic2::{Topic, TopicRef, TopicRefMut, TopicRoot},
+        },
     },
-    streaming::topics::topic2::{Topic, TopicRef, TopicRefMut, TopicRoot},
 };
-use iggy_common::{CompressionAlgorithm, Identifier, IggyExpiry, MaxTopicSize};
+use iggy_common::{
+    CompressionAlgorithm, ConsumerGroup, ConsumerGroupMember, Identifier, IggyExpiry, MaxTopicSize,
+};
+use slab::Slab;
 
 pub fn rename_index(
     old_name: &<TopicRoot as Keyed>::Key,
@@ -21,21 +42,63 @@ pub fn rename_index(
     }
 }
 
+// Partitions
+pub fn delete_partitions(
+    partitions_count: u32,
+) -> impl FnOnce(ComponentsById<TopicRefMut>) -> Vec<u32> {
+    move |(mut root, _)| {
+        let partitions = root.partitions_mut();
+        let current_count = partitions.len() as u32;
+        let partitions_to_delete = partitions_count.min(current_count);
+        let start_idx = (current_count - partitions_to_delete) as usize;
+        let mut deleted_ids = Vec::with_capacity(partitions_to_delete as usize);
+        for idx in start_idx..current_count as usize {
+            let partition = partitions.delete(idx);
+            assert_eq!(partition.id(), idx);
+            deleted_ids.push(partition.id() as u32);
+        }
+        deleted_ids
+    }
+}
+
+pub fn insert_partition(
+    partition: partition2::Partition,
+) -> impl FnOnce(ComponentsById<TopicRefMut>) -> partitions::ContainerId {
+    move |(mut root, _)| root.partitions_mut().insert(partition)
+}
+
+// Topics
+pub fn get_stats() -> impl FnOnce(ComponentsById<TopicRef>) -> Arc<TopicStats> {
+    |(_, stats)| stats.clone()
+}
+
 pub fn get_topic_id() -> impl FnOnce(ComponentsById<TopicRef>) -> topics::ContainerId {
     |(root, _)| root.id()
 }
 
+pub fn get_message_expiry() -> impl FnOnce(ComponentsById<TopicRef>) -> IggyExpiry {
+    |(root, _)| root.message_expiry()
+}
+
+pub fn get_max_topic_size() -> impl FnOnce(ComponentsById<TopicRef>) -> MaxTopicSize {
+    |(root, _)| root.max_topic_size()
+}
+
 pub fn delete_topic(topic_id: &Identifier) -> impl FnOnce(&Topics) -> Topic {
-    move |topics| {
-        let id = topics.get_index(topic_id);
-        let topic = topics.delete(id);
+    |container| {
+        let id = container.get_index(topic_id);
+        let topic = container.delete(id);
         assert_eq!(topic.id(), id, "delete_topic: topic ID mismatch");
         topic
     }
 }
 
 pub fn exists(identifier: &Identifier) -> impl FnOnce(&Topics) -> bool {
-    move |topics| topics.exists(identifier)
+    |topics| topics.exists(identifier)
+}
+
+pub fn cg_exists(identifier: &Identifier) -> impl FnOnce(ComponentsById<TopicRef>) -> bool {
+    |(root, ..)| root.consumer_groups().exists(identifier)
 }
 
 pub fn update_topic(
@@ -56,3 +119,167 @@ pub fn update_topic(
         // TODO: Set message expiry for all partitions and segments.
     }
 }
+
+// Consumer Groups
+pub fn delete_consumer_group(
+    group_id: &Identifier,
+) -> impl FnOnce(&mut ConsumerGroups) -> consumer_group2::ConsumerGroup {
+    |container| {
+        let id = container.get_index(group_id);
+        let group = container.delete(id);
+        assert_eq!(group.id(), id, "delete_consumer_group: group ID mismatch");
+        group
+    }
+}
+
+pub fn join_consumer_group(
+    shard_id: u16,
+    client_id: u32,
+) -> impl FnOnce(ComponentsById<ConsumerGroupRefMut>) {
+    move |(root, members)| {
+        let partitions = root.partitions();
+        let id = root.id();
+        add_member(shard_id, id, members, partitions, client_id);
+    }
+}
+
+fn add_member(
+    shard_id: u16,
+    id: usize,
+    members: &mut ConsumerGroupMembers,
+    partitions: &Vec<usize>,
+    client_id: u32,
+) {
+    members.inner_mut().rcu(move |members| {
+        let mut members = mimic_members(members);
+        Member::new(client_id).insert_into(&mut members);
+        assign_partitions_to_members(shard_id, id, &mut members, partitions.clone());
+        members
+    });
+}
+
+fn delete_member(shard_id: u16, id: usize, members: &mut ConsumerGroupMembers, partitions: &Vec<usize>, client_id: u32) {
+    let member_id = members
+        .inner()
+        .shared_get()
+        .iter()
+        .find_map(|(_, member)| (member.client_id == client_id).then_some(member.id))
+        .expect("delete_member: find member in consumer group slab");
+    members.inner_mut().rcu(|members| {
+        let mut members = mimic_members(members);
+        members.remove(member_id);
+        members.compact(|entry, _, idx| {
+            entry.id = idx;
+            true
+        });
+        assign_partitions_to_members(shard_id, id, &mut members, partitions.clone());
+        members
+    });
+}
+
+fn assign_partitions_to_members(
+    shard_id: u16,
+    id: usize,
+    members: &mut Slab<Member>,
+    partitions: Vec<usize>,
+) {
+    members
+        .iter_mut()
+        .for_each(|(_, member)| member.partitions.clear());
+    let count = members.len();
+    for (idx, partition) in partitions.iter().enumerate() {
+        let position = idx % count;
+        let member = &mut members[position];
+        member.partitions.push(*partition);
+        shard_trace!(
+            shard_id,
+            "Assigned partition ID: {} to member with ID: {} in consumer group: {}",
+            partition,
+            member.id,
+            id
+        );
+    }
+}
+fn mimic_members(members: &Slab<Member>) -> Slab<Member> {
+    let mut container = Slab::with_capacity(members.len());
+    for (_, member) in members {
+        Member::new(member.client_id).insert_into(&mut container);
+    }
+    container
+}
+
+pub fn reassign_partitions(
+    shard_id: u16,
+    partitions: Vec<partitions::ContainerId>,
+) -> impl FnOnce(ComponentsById<ConsumerGroupRefMut>) {
+    move |(mut root, members)| {
+        root.partitions_mut() = partitions;
+        let partitions = root.partitions();
+        let id = root.id();
+        reassign_partitions_to_members(shard_id, id, members, partitions);
+    }
+}
+
+fn reassign_partitions_to_members(
+    shard_id: u16,
+    id: usize,
+    members: &mut ConsumerGroupMembers,
+    partitions: &Vec<usize>,
+) {
+    members.inner_mut().rcu(move |members| {
+        let mut members = mimic_members(members);
+        assign_partitions_to_members(shard_id, id, &mut members, partitions.clone());
+        members
+    });
+}
+
+pub fn calculate_partition_id_unchecked(
+    member_id: usize,
+) -> impl FnOnce(ComponentsById<ConsumerGroupRef>) -> Option<usize> {
+    move |(_, members)| {
+            let members = members.inner();
+            let member = &members[member_id];
+            if member.partitions.is_empty() {
+                return None;
+            }
+
+            let partitions_count = member.partitions.len();
+            // It's OK to use `Relaxed` ordering, because we have 1-1 mapping between consumer and member.
+            // We allow only one consumer to access topic in a given shard
+            // therefore there is no contention on the member's current partition index.
+            let current = member
+                .current_partition_idx
+                .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
+                    Some((current + 1) % partitions_count)
+                })
+                .expect("fetch_and_update partition id for consumer group member");
+            Some(member.partitions[current])
+        }
+}
+
+pub fn get_current_partition_id_unchecked(
+    member_id: usize,
+) -> impl FnOnce(ComponentsById<ConsumerGroupRef>) -> Option<usize> {
+    move |(_, members)| {
+        members.inner().with_shared(|members| {
+            let member = &members[member_id];
+            if member.partitions.is_empty() {
+                return None;
+            }
+
+            let partition_idx = member.current_partition_idx.load(Ordering::Relaxed);
+            Some(member.partitions[partition_idx])
+        })
+    }
+}
+
+pub fn leave_consumer_group(
+    shard_id: u16,
+    client_id: u32,
+) -> impl FnOnce(ComponentsById<ConsumerGroupRefMut>) {
+    move |(root, members)| {
+        let partitions = root.partitions();
+        let id = root.id();
+        delete_member(shard_id, id, members, partitions, client_id);
+    }
+}
\ No newline at end of file
diff --git a/core/server/src/streaming/topics/topic2.rs b/core/server/src/streaming/topics/topic2.rs
index 3f930990..10f6fc3e 100644
--- a/core/server/src/streaming/topics/topic2.rs
+++ b/core/server/src/streaming/topics/topic2.rs
@@ -2,7 +2,7 @@ use crate::configs::system::SystemConfig;
 use crate::slab::topics;
 use crate::slab::traits_ext::{EntityMarker, IntoComponents, IntoComponentsById};
 use crate::slab::{Keyed, consumer_groups::ConsumerGroups, partitions::Partitions};
-use crate::streaming::stats::stats::{PartitionStats, TopicStats};
+use crate::streaming::stats::stats::TopicStats;
 use iggy_common::{CompressionAlgorithm, IggyError, IggyExpiry, IggyTimestamp, MaxTopicSize};
 use slab::Slab;
 use std::cell::{Ref, RefMut};
@@ -183,11 +183,8 @@ impl TopicRoot {
         f(self).await
     }
 
-    pub fn with_partition_stats_mut<T>(
-        &mut self,
-        f: impl FnOnce(&mut Slab<Arc<PartitionStats>>) -> T,
-    ) -> T {
-        self.partitions.with_stats_mut(f)
+    pub fn id(&self) -> topics::ContainerId {
+        self.id
     }
 
     pub fn message_expiry(&self) -> IggyExpiry {
@@ -198,10 +195,6 @@ impl TopicRoot {
         self.max_topic_size
     }
 
-    pub fn id(&self) -> usize {
-        self.id
-    }
-
     pub fn name(&self) -> &String {
         &self.name
     }
@@ -242,13 +235,6 @@ impl TopicRoot {
         &mut self.consumer_groups
     }
 
-    pub fn insert_into(self, container: &mut Slab<Self>) -> usize {
-        let idx = container.insert(self);
-        let topic = &mut container[idx];
-        topic.id = idx;
-        idx
-    }
-
     pub fn created_at(&self) -> IggyTimestamp {
         self.created_at
     }