Skip to content

Commit 2f847d5

Browse files
authored
region cache: limit key ranges sent to PD in one BatchScanRegions gRPC (tikv#1712)
close tikv#1704 Signed-off-by: you06 <you1474600@gmail.com>
1 parent e60fec1 commit 2f847d5

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

internal/locate/region_cache.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1350,7 +1350,16 @@ func (c *RegionCache) BatchLocateKeyRanges(bo *retry.Backoffer, keyRanges []kv.K
13501350

13511351
// 2. load remaining regions from pd client
13521352
for len(uncachedRanges) > 0 {
1353-
regions, err := c.BatchLoadRegionsWithKeyRanges(bo, uncachedRanges, defaultRegionsPerBatch, opts...)
1353+
// If we send too many ranges to PD, it may exceed the size of grpc limitation or cause a timeout error.
1354+
// So we limit the number of ranges per batch to avoid this issue.
1355+
maxRangesPerBatch := 16 * defaultRegionsPerBatch
1356+
var toBeSentRanges []router.KeyRange
1357+
if len(uncachedRanges) > maxRangesPerBatch {
1358+
toBeSentRanges = uncachedRanges[:maxRangesPerBatch]
1359+
} else {
1360+
toBeSentRanges = uncachedRanges
1361+
}
1362+
regions, err := c.BatchLoadRegionsWithKeyRanges(bo, toBeSentRanges, defaultRegionsPerBatch, opts...)
13541363
if err != nil {
13551364
return nil, err
13561365
}

internal/locate/region_cache_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3086,3 +3086,25 @@ func (s *testRegionCacheSuite) TestRegionCacheValidAfterLoading() {
30863086
s.True(region.isValid())
30873087
}
30883088
}
3089+
3090+
func (s *testRegionCacheSuite) TestBatchLoadLimitRanges() {
3091+
ranges := make([]kv.KeyRange, 0, 100000)
3092+
for i := 0; i < 100000; i++ {
3093+
startKey := make([]byte, 8)
3094+
endKey := make([]byte, 8)
3095+
binary.BigEndian.PutUint64(startKey, uint64(i*2))
3096+
binary.BigEndian.PutUint64(endKey, uint64(i*2+1))
3097+
ranges = append(ranges, kv.KeyRange{StartKey: startKey, EndKey: endKey})
3098+
}
3099+
3100+
originalBatchScanRegions := s.cache.pdClient.BatchScanRegions
3101+
s.cache.pdClient = &inspectedPDClient{
3102+
Client: s.cache.pdClient,
3103+
batchScanRegions: func(ctx context.Context, keyRanges []router.KeyRange, limit int, opts ...opt.GetRegionOption) ([]*router.Region, error) {
3104+
s.LessOrEqual(len(keyRanges), 16*defaultRegionsPerBatch)
3105+
return originalBatchScanRegions(ctx, keyRanges, limit, opts...)
3106+
},
3107+
}
3108+
_, err := s.cache.BatchLocateKeyRanges(s.bo, ranges)
3109+
s.Nil(err)
3110+
}

0 commit comments

Comments
 (0)