Skip to content

Commit

Permalink
Rate Limit Scan Statistics
Browse files Browse the repository at this point in the history
This pull request uses a `TokenBucket` to limit the number of keys that
read from `ScanStatistics` within a certain period of time.

Fixes: #2778
  • Loading branch information
raggar committed Jul 31, 2023
1 parent 127a180 commit b52a152
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/vfs"
"github.com/cockroachdb/pebble/vfs/atomicfs"
"github.com/cockroachdb/tokenbucket"
"github.com/prometheus/client_golang/prometheus"
)

Expand Down Expand Up @@ -2604,9 +2605,21 @@ type LSMKeyStatistics struct {
func (d *DB) ScanStatistics(ctx context.Context, lower, upper []byte) (LSMKeyStatistics, error) {
stats := LSMKeyStatistics{}
var prevKey InternalKey
tb := tokenbucket.TokenBucket{}
tb.Init(50, 50)

rateLimit := func() {
fulfilled, tryAgainAfter := tb.TryToFulfill(1)

if !fulfilled {
time.Sleep(tryAgainAfter)
}
}

err := d.ScanInternal(ctx, lower, upper,
func(key *InternalKey, value LazyValue, iterInfo iterInfo) error {
rateLimit()

// iterInfo.level == -1 indicates that the key does not come from a valid level.
if iterInfo.level == -1 {
return nil
Expand All @@ -2628,10 +2641,12 @@ func (d *DB) ScanStatistics(ctx context.Context, lower, upper []byte) (LSMKeySta
return nil
},
func(start, end []byte, seqNum uint64) error {
rateLimit()
stats.accumulated.kindsCount[InternalKeyKindRangeDelete]++
return nil
},
func(start, end []byte, keys []rangekey.Key) error {
rateLimit()
for _, key := range keys {
stats.accumulated.kindsCount[key.Kind()]++
}
Expand Down

0 comments on commit b52a152

Please sign in to comment.