Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/storage/db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ derive_more.workspace = true
rustc-hash = { workspace = true, optional = true, features = ["std"] }
sysinfo = { workspace = true, features = ["system"] }
parking_lot = { workspace = true, optional = true }
dashmap.workspace = true

# arbitrary utils
strum = { workspace = true, features = ["derive"], optional = true }
Expand Down Expand Up @@ -91,6 +92,7 @@ arbitrary = [
"alloy-consensus/arbitrary",
"reth-primitives-traits/arbitrary",
"reth-prune-types/arbitrary",
"dashmap/arbitrary",
]
op = [
"reth-db-api/op",
Expand Down
27 changes: 20 additions & 7 deletions crates/storage/db/src/implementation/mdbx/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::{
metrics::{DatabaseEnvMetrics, Operation, TransactionMode, TransactionOutcome},
DatabaseError,
};
use dashmap::DashMap;
use reth_db_api::{
table::{Compress, DupSort, Encode, Table, TableImporter},
transaction::{DbTx, DbTxMut},
Expand All @@ -31,6 +32,10 @@ pub struct Tx<K: TransactionKind> {
/// Libmdbx-sys transaction.
pub inner: Transaction<K>,

/// Cached MDBX DBIs for reuse.
/// TODO: Reuse DBIs even among transactions, ideally with no synchronization overhead.
dbis: DashMap<&'static str, MDBX_dbi>,

/// Handler for metrics with its own [Drop] implementation for cases when the transaction isn't
/// closed by [`Tx::commit`] or [`Tx::abort`], but we still need to report it in the metrics.
///
Expand All @@ -41,7 +46,7 @@ pub struct Tx<K: TransactionKind> {
impl<K: TransactionKind> Tx<K> {
/// Creates new `Tx` object with a `RO` or `RW` transaction.
#[inline]
pub const fn new(inner: Transaction<K>) -> Self {
pub fn new(inner: Transaction<K>) -> Self {
Self::new_inner(inner, None)
}

Expand All @@ -64,8 +69,8 @@ impl<K: TransactionKind> Tx<K> {
}

#[inline]
const fn new_inner(inner: Transaction<K>, metrics_handler: Option<MetricsHandler<K>>) -> Self {
Self { inner, metrics_handler }
fn new_inner(inner: Transaction<K>, metrics_handler: Option<MetricsHandler<K>>) -> Self {
Self { inner, metrics_handler, dbis: DashMap::new() }
}

/// Gets this transaction ID.
Expand All @@ -75,10 +80,18 @@ impl<K: TransactionKind> Tx<K> {

/// Gets a table database handle if it exists, otherwise creates it.
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unfamiliar with the internals here, but can we safely assume that this will always exist for the duration of the transaction?

maybe @shekhirin knows

Copy link
Copy Markdown
Contributor Author

@hai-rise hai-rise Sep 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MDBX_dbi is an index/pointer to the actual table handle stored in the DB environment, which will live until the end of the environment, basically the end of the program for Reth, or until it is explicitly closed via mdbx_dbi_close, which we don't and shouldn't do.

Since we don't dynamically create new tables at runtime (right?), the best practice is to pre-create all these table handles at startup time, then share their MDBX_dbis across all transactions.

Otherwise, (repeatedly) calling mdbx_dbi_open at runtime is very expensive. In the code path I showed earlier in #18284, 2.5 / 5.1 ~ 49% of the get (stage checkpoint) is spent on open_db, which likely returns the same MDBX_dbi anyway. Just much more expensive as it needs to execute a transaction, creates contention at the DB-level, etc.

image

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds correct, confirmed with MDBX documentation https://libmdbx.dqdkfa.ru/group__c__dbi.html#ga9bef4a9fdf27655e9343bbbf8b6fc5a1

pub fn get_dbi<T: Table>(&self) -> Result<MDBX_dbi, DatabaseError> {
self.inner
.open_db(Some(T::NAME))
.map(|db| db.dbi())
.map_err(|e| DatabaseError::Open(e.into()))
match self.dbis.entry(T::NAME) {
dashmap::Entry::Occupied(occ) => Ok(*occ.get()),
dashmap::Entry::Vacant(vac) => {
let dbi = self
.inner
.open_db(Some(T::NAME))
.map(|db| db.dbi())
.map_err(|e| DatabaseError::Open(e.into()))?;
vac.insert(dbi);
Ok(dbi)
}
}
}

/// Create db Cursor
Expand Down
Loading