Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
161: Building a Distributed Rate Limiter
Wait, why can't I just use an AtomicInteger in a singleton?
If you're running a single instance of your application on one server, an AtomicInteger or a ConcurrentHashMap is perfect. It's fast and simple. But the second you scale to two or more nodes behind a load balancer, that strategy falls apart.
Imagine you've set a limit of 100 requests per minute. User A hits Server 1, then Server 2, then Server 1 again. If each server is tracking the count locally, User A could potentially make 100 requests per server. Suddenly, your "100 request limit" is actually 1,000 requests if you have ten nodes. To solve this, we need a shared state—something external to the JVM. Redis is the industry standard here because it's an in-memory store that's fast enough to handle the overhead of every single request checking in.
If I fetch the count and then increment it, won't I have a race condition?
Exactly. This is the classic "read-modify-write" problem. If two requests hit two different servers at the exact same millisecond, they both read the value 49, both think it's under the limit of 50, and both increment it to 50. You've just let 51 requests through.
I usually handle this using Lua scripts in Redis. Redis guarantees that a Lua script runs atomically. Instead of bringing the data to Scala, we send the logic to the data. Here is how I'd structure a simple fixed-window limiter in Scala:
case class RateLimitResult(allowed: Boolean, remaining: Long)
def checkLimit(userId: String, limit: Long, windowSeconds: Int): RateLimitResult = {
val luaScript =
"""
local current = redis.call('INCR', KEYS[1])
if current == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[1])
end
return current
""".stripMargin
// We use the userId and the current minute as the key to create a fixed window
val windowKey = s"rate_limit:$userId:${System.currentTimeMillis() / 60000}"
val count = redisClient.eval(luaScript, Seq(windowKey), Seq(windowSeconds.toString)).toLong
RateLimitResult(count <= limit, limit - count)
}
By using INCR and EXPIRE inside a script, we ensure that the increment and the TTL (Time To Live) are set without any other request sneaking in between.
Fixed windows feel clunky—how do I stop "bursts" at the edge of a minute?
You've hit on the biggest weakness of fixed windows. If a user sends 100 requests at 10:00:59 and another 100 at 10:01:01, they've technically stayed within the "per minute" limit, but they just slammed your API with 200 requests in two seconds. It's a great way to crash a database.
To fix this, I use a Sliding Window Log. Instead of a single counter, we store every request timestamp in a Redis Sorted Set (ZSET). When a request comes in, we remove all timestamps older than the current window, count what's left, and then decide if we allow the new request.
def checkSlidingWindow(userId: String, limit: Long, windowMillis: Long): Boolean = {
val now = System.currentTimeMillis()
val windowStart = now - windowMillis
val key = s"sliding_limit:$userId"
// Use a Redis pipeline or Lua script to make this atomic
redisClient.multi {
// 1. Remove timestamps older than the current window
redisClient.zremrangebyscore(key, 0, windowStart)
// 2. Count elements remaining in the set
val count = redisClient.zcard(key)
if (count < limit) {
// 3. Add the current request timestamp
redisClient.zadd(key, now.toDouble, now.toString)
true
} else {
false
}
}
}
It's a bit more expensive in terms of memory because you're storing every timestamp, but for most high-value APIs, the precision is worth the cost. If you're dealing with millions of users and billions of requests, you might want to look into the Generic Cell Rate Algorithm (GCRA), but that's a deeper rabbit hole for another time.
📋 Practical Task
Implement a Redis-backed Sliding Window Pruner
You are tasked with optimizing a distributed rate limiter. The current implementation is leaking memory because it adds timestamps to the Redis Sorted Set but doesn't efficiently clean them up.
Write a Scala function pruneAndCheck that takes a userId, a limit, and a windowMillis. The function must:
- Use a Redis Sorted Set (ZSET) where the score and value are both the current timestamp.
- Remove all entries older than
currentTime - windowMillis. - Check if the number of remaining entries is less than the
limit. - If allowed, add the current timestamp to the set and return
true. Otherwise, returnfalse.
Constraints: Assume you have a redis client object available with methods zremrangebyscore(key, min, max), zcard(key), and zadd(key, score, member).
There are no comments for now.