-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: use singleton rate limiter to prevent creation of multiple limit…
…er when there is more than 1 partition
- Loading branch information
1 parent
f739ac2
commit a1564db
Showing
2 changed files
with
30 additions
and
11 deletions.
There are no files selected for viewing
29 changes: 29 additions & 0 deletions
29
caraml-store-spark/src/main/scala/dev/caraml/spark/stores/redis/RateLimiter.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package dev.caraml.spark.stores.redis | ||
|
||
import dev.caraml.spark.RedisWriteProperties | ||
import io.github.bucket4j.{Bandwidth, Bucket} | ||
|
||
import java.time.Duration.ofSeconds | ||
import java.util.concurrent.ConcurrentHashMap | ||
|
||
object RateLimiter { | ||
|
||
private lazy val buckets: ConcurrentHashMap[RedisWriteProperties, Bucket] = new ConcurrentHashMap | ||
|
||
def get(properties: RedisWriteProperties): Bucket = { | ||
buckets.computeIfAbsent(properties, create) | ||
} | ||
|
||
def create(properties: RedisWriteProperties): Bucket = { | ||
Bucket | ||
.builder() | ||
.addLimit( | ||
Bandwidth | ||
.builder() | ||
.capacity(properties.ratePerSecondLimit) | ||
.refillIntervally(properties.ratePerSecondLimit, ofSeconds(1)) | ||
.build() | ||
) | ||
.build() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters