-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
240: Practice Exercise: Building an Actor-Based Rate Limiter
I remember a project a few years back where we were integrating a legacy banking API. The documentation explicitly stated a limit of "5 requests per second," but it didn't mention how strictly they enforced it. We had a bunch of concurrent Task blocks firing off to populate a dashboard, and within milliseconds, we were hitting 429 "Too Many Requests" errors. The problem wasn't that we were sending too many requests overall, but that we were sending them all at the exact same instant. We needed a way to serialize these requests and force a gap between them, regardless of which part of the app was triggering the call.
This is where an actor becomes your best friend. Because actors guarantee mutually exclusive access to their internal state, they are the perfect mechanism for a rate limiter. You can keep track of when the last request was sent and force the current caller to wait if they're moving too fast. Since the actor handles the synchronization, you don't have to mess around with locks or semaphores, which—let's be honest—is a recipe for deadlocks if you aren't extremely careful.
Synchronizing Request Intervals
The core of a rate limiter is simply tracking a timestamp. When a request comes in, the actor checks the difference between the current time and the last successful request. If the gap is smaller than your allowed threshold, the actor uses Task.sleep to pause the execution. Because the actor processes messages one at a time, subsequent requests will queue up behind the sleeping task, naturally spacing them out.
actor RateLimiter {
private let minInterval: Duration
private var lastRequestDate = ContinuousClock.now - minInterval
init(requestsPerSecond: Double) {
// Calculate the gap required between requests
self.minInterval = .seconds(1.0 / requestsPerSecond)
}
func execute<T>(operation: () async throws -> T) async rethrows -> T {
let now = ContinuousClock.now
let elapsed = now - lastRequestDate
if elapsed < minInterval {
let delay = minInterval - elapsed
try await Task.sleep(for: delay)
}
// Update the timestamp after the potential sleep
lastRequestDate = ContinuousClock.now
return try await operation()
}
}
Avoiding the "Thundering Herd"
One thing I've noticed developers struggle with is the difference between throttling and rate limiting. Throttling usually means "ignore everything until a timer expires." Rate limiting, as we've implemented it here, means "ensure every request eventually happens, but space them out."
By using try await Task.sleep inside the actor, we aren't blocking the underlying thread. The thread is freed up to do other work while the specific task associated with that request is suspended. When the timer hits, the task resumes, updates the lastRequestDate, and finally executes the operation. This ensures that even if you fire 100 requests simultaneously, they will bleed out one by one at exactly the rate you specified, without freezing your UI or crashing your app.
📋 Practical Task
Exercise: Building a Token-Bucket Rate Limiter
In a real-world scenario, a strict "one-by-one" gap is often too rigid. Most APIs use a "Token Bucket" algorithm: you can send a burst of requests (the bucket size), but once the bucket is empty, you must wait for tokens to refill at a steady rate.
Your task is to modify the RateLimiter actor to implement this burst logic. Build a TokenBucketLimiter actor with the following requirements:
- Properties:
maxTokens: The maximum number of requests allowed in a burst.refillRate: How many tokens are added back per second.availableTokens: A current count of tokens.lastRefillTime: A timestamp of when the tokens were last updated.
- Logic:
- Every time
executeis called, first calculate how many new tokens should have been added sincelastRefillTimebased on therefillRate. - Add those tokens to
availableTokens, capping it atmaxTokens. - If
availableTokensis > 0, decrement a token and execute the operation immediately. - If
availableTokensis 0, calculate the time remaining until at least one token becomes available,await Task.sleepfor that duration, then refill and execute.
- Every time
Test your implementation by spawning 20 concurrent tasks that attempt to print "Request sent" using the limiter, ensuring the first burst happens instantly and the remainder are spaced out according to your refill rate.
There are no comments for now.