Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Perf] Add cache for most recent blocks #3440

Open
wants to merge 3 commits into
base: staging
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions Cargo.lock

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

6 changes: 5 additions & 1 deletion node/bft/ledger-service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ edition = "2021"

[features]
default = [ ]
ledger = [ "lru", "parking_lot", "rand", "tokio", "tracing" ]
ledger = [ "lru", "parking_lot", "rand", "rayon", "tokio", "tracing" ]
ledger-write = [ ]
metrics = [ "dep:metrics", "snarkvm/metrics" ]
mock = [ "parking_lot", "tracing" ]
Expand Down Expand Up @@ -52,6 +52,10 @@ optional = true
version = "0.8"
optional = true

[dependencies.rayon]
version = "1"
optional = true

[dependencies.snarkvm]
workspace = true

Expand Down
24 changes: 20 additions & 4 deletions node/bft/ledger-service/src/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ use snarkvm::{
puzzle::{Solution, SolutionID},
store::ConsensusStorage,
},
prelude::{Address, Field, FromBytes, Network, Result, bail},
prelude::{Address, Field, FromBytes, Network, Result, bail, cfg_into_iter},
};

use indexmap::IndexMap;
use lru::LruCache;
use parking_lot::{Mutex, RwLock};
use rayon::prelude::*;
use std::{
collections::BTreeMap,
fmt,
io::Read,
ops::Range,
Expand All @@ -41,12 +43,15 @@ use std::{

/// The capacity of the LRU holding the recently queried committees.
const COMMITTEE_CACHE_SIZE: usize = 16;
/// The capacity of the cache holding the highest blocks.
const BLOCK_CACHE_SIZE: usize = 10;
vicsn marked this conversation as resolved.
Show resolved Hide resolved

/// A core ledger service.
#[allow(clippy::type_complexity)]
pub struct CoreLedgerService<N: Network, C: ConsensusStorage<N>> {
ledger: Ledger<N, C>,
committee_cache: Arc<Mutex<LruCache<u64, Committee<N>>>>,
block_cache: Arc<RwLock<BTreeMap<u32, Block<N>>>>,
latest_leader: Arc<RwLock<Option<(u64, Address<N>)>>>,
shutdown: Arc<AtomicBool>,
}
Expand All @@ -55,7 +60,8 @@ impl<N: Network, C: ConsensusStorage<N>> CoreLedgerService<N, C> {
/// Initializes a new core ledger service.
pub fn new(ledger: Ledger<N, C>, shutdown: Arc<AtomicBool>) -> Self {
let committee_cache = Arc::new(Mutex::new(LruCache::new(COMMITTEE_CACHE_SIZE.try_into().unwrap())));
Self { ledger, committee_cache, latest_leader: Default::default(), shutdown }
let block_cache = Arc::new(RwLock::new(BTreeMap::new()));
Self { ledger, committee_cache, block_cache, latest_leader: Default::default(), shutdown }
}
}

Expand Down Expand Up @@ -120,13 +126,17 @@ impl<N: Network, C: ConsensusStorage<N>> LedgerService<N> for CoreLedgerService<

/// Returns the block for the given block height.
fn get_block(&self, height: u32) -> Result<Block<N>> {
self.ledger.get_block(height)
if let Some(block) = self.block_cache.read().get(&height) {
Ok(block.clone())
} else {
self.ledger.get_block(height)
}
}

/// Returns the blocks in the given block range.
/// The range is inclusive of the start and exclusive of the end.
fn get_blocks(&self, heights: Range<u32>) -> Result<Vec<Block<N>>> {
self.ledger.get_blocks(heights)
cfg_into_iter!(heights).map(|height| self.get_block(height)).collect()
}

/// Returns the solution for the given solution ID.
Expand Down Expand Up @@ -365,6 +375,12 @@ impl<N: Network, C: ConsensusStorage<N>> LedgerService<N> for CoreLedgerService<
}
// Advance to the next block.
self.ledger.advance_to_next_block(block)?;
// Add the block to the block cache.
self.block_cache.write().insert(block.height(), block.clone());
// Prune the block cache if it exceeds the maximum size.
if self.block_cache.read().len() > BLOCK_CACHE_SIZE {
self.block_cache.write().pop_first();
}
// Update BFT metrics.
#[cfg(feature = "metrics")]
{
Expand Down