From 248dfce9c1191cec4f63e824a2ef658373bfc0d5 Mon Sep 17 00:00:00 2001 From: Martin Boehm Date: Fri, 21 May 2021 15:15:28 +0200 Subject: [PATCH] Improve caching of estimate fee call --- api/worker.go | 55 ++++++++++++++++++++++----------------------------- 1 file changed, 24 insertions(+), 31 deletions(-) diff --git a/api/worker.go b/api/worker.go index 639d8eea3e..31328a7980 100644 --- a/api/worker.go +++ b/api/worker.go @@ -10,6 +10,7 @@ import ( "sort" "strconv" "strings" + "sync" "time" "github.com/golang/glog" @@ -1823,48 +1824,40 @@ func (w *Worker) GetMempool(page int, itemsOnPage int) (*MempoolTxids, error) { } type bitcoinTypeEstimatedFee struct { - accessed int64 - fee big.Int + timestamp int64 + fee big.Int + lock sync.Mutex } -const bitcoinTypeEstimatedFeeCacheSize = 250 +const bitcoinTypeEstimatedFeeCacheSize = 300 var bitcoinTypeEstimatedFeeCache [bitcoinTypeEstimatedFeeCacheSize]bitcoinTypeEstimatedFee var bitcoinTypeEstimatedFeeConservativeCache [bitcoinTypeEstimatedFeeCacheSize]bitcoinTypeEstimatedFee +func (w *Worker) cachedBitcoinTypeEstimateFee(blocks int, conservative bool, s *bitcoinTypeEstimatedFee) (big.Int, error) { + s.lock.Lock() + defer s.lock.Unlock() + // 10 seconds cache + threshold := time.Now().Unix() - 10 + if s.timestamp >= threshold { + return s.fee, nil + } + fee, err := w.chain.EstimateSmartFee(blocks, conservative) + if err == nil { + s.timestamp = time.Now().Unix() + s.fee = fee + } + return fee, err +} + // BitcoinTypeEstimateFee returns a fee estimation for given number of blocks -// it uses 5 second cache to reduce calls to the backend +// it uses 10 second cache to reduce calls to the backend func (w *Worker) BitcoinTypeEstimateFee(blocks int, conservative bool) (big.Int, error) { if blocks >= bitcoinTypeEstimatedFeeCacheSize { return w.chain.EstimateSmartFee(blocks, conservative) } - // 5 seconds cache - threshold := time.Now().Unix() - 5 if conservative { - cached := bitcoinTypeEstimatedFeeConservativeCache[blocks] - if cached.accessed >= threshold { - return cached.fee, nil - } - fee, err := w.chain.EstimateSmartFee(blocks, conservative) - if err == nil { - bitcoinTypeEstimatedFeeConservativeCache[blocks] = bitcoinTypeEstimatedFee{ - accessed: time.Now().Unix(), - fee: fee, - } - } - return fee, err - } else { - cached := bitcoinTypeEstimatedFeeCache[blocks] - if cached.accessed >= threshold { - return cached.fee, nil - } - fee, err := w.chain.EstimateSmartFee(blocks, conservative) - if err == nil { - bitcoinTypeEstimatedFeeCache[blocks] = bitcoinTypeEstimatedFee{ - accessed: time.Now().Unix(), - fee: fee, - } - } - return fee, err + return w.cachedBitcoinTypeEstimateFee(blocks, conservative, &bitcoinTypeEstimatedFeeConservativeCache[blocks]) } + return w.cachedBitcoinTypeEstimateFee(blocks, conservative, &bitcoinTypeEstimatedFeeCache[blocks]) }