@@ -314,6 +314,8 @@ proc updateBase(c: ForkedChainRef, base: BlockRef): uint =
314314 # No update, return
315315 return
316316
317+ let startTime = Moment .now ()
318+
317319 # State root sanity check is performed to verify, before writing to disk,
318320 # that optimistically checked blocks indeed end up being stored with a
319321 # consistent state root.
@@ -338,8 +340,7 @@ with --debug-eager-state-root."""
338340
339341 # Cleanup in-memory blocks starting from base backward
340342 # e.g. B2 backward.
341- var
342- count = 0 'u
343+ var count = 0 'u
343344
344345 for it in ancestors (base.parent):
345346 c.removeBlockFromCache (it)
@@ -352,6 +353,33 @@ with --debug-eager-state-root."""
352353 # Base block always have finalized marker
353354 c.base.finalize ()
354355
356+ if c.dynamicBatchSize:
357+ # Dynamicly adjust the persistBatchSize based on the recorded run time.
358+ # The goal here is use the maximum batch size possible without blocking the
359+ # event loop for too long which could negatively impact the p2p networking.
360+ # Increasing the batch size can improve performance because the stateroot
361+ # computation and persist calls are performed less frequently.
362+ const
363+ targetTime = 500 .milliseconds
364+ targetTimeDelta = 200 .milliseconds
365+ targetTimeLowerBound = (targetTime - targetTimeDelta).milliseconds
366+ targetTimeUpperBound = (targetTime + targetTimeDelta).milliseconds
367+ batchSizeLowerBound = 4
368+ batchSizeUpperBound = 512
369+
370+ let
371+ finishTime = Moment .now ()
372+ runTime = (finishTime - startTime).milliseconds
373+
374+ if runTime < targetTimeLowerBound and c.persistBatchSize <= batchSizeUpperBound:
375+ c.persistBatchSize *= 2
376+ info " Increased persistBatchSize" , runTime, targetTime,
377+ persistBatchSize = c.persistBatchSize
378+ elif runTime > targetTimeUpperBound and c.persistBatchSize >= batchSizeLowerBound:
379+ c.persistBatchSize = c.persistBatchSize div 2
380+ info " Decreased persistBatchSize" , runTime, targetTime,
381+ persistBatchSize = c.persistBatchSize
382+
355383 count
356384
357385proc processUpdateBase (c: ForkedChainRef ): Future [Result [void , string ]] {.async : (raises: [CancelledError ]).} =
@@ -586,6 +614,7 @@ proc init*(
586614 com: CommonRef ;
587615 baseDistance = BaseDistance ;
588616 persistBatchSize = PersistBatchSize ;
617+ dynamicBatchSize = false ;
589618 eagerStateRoot = false ;
590619 enableQueue = false ;
591620 ): T =
@@ -627,6 +656,7 @@ proc init*(
627656 baseTxFrame: baseTxFrame,
628657 baseDistance: baseDistance,
629658 persistBatchSize: persistBatchSize,
659+ dynamicBatchSize: dynamicBatchSize,
630660 quarantine: Quarantine .init (),
631661 fcuHead: fcuHead,
632662 fcuSafe: fcuSafe,
0 commit comments