Test an iOS token bucket with deterministic time on a cloud Mac
When a rate-limit test occasionally lets one extra request through during a remote run, it is easy to blame machine load. The real problem is often using sleep to guess when a refill will happen: if the thread wakes a few milliseconds late, the test crosses the boundary. Extract the token bucket at your iOS request entry point into a pure state machine and pass explicit timestamps on a cloud Mac. That lets you distinguish algorithm bugs from scheduling delays.
Define the capacity and refill contract first
This article uses a discrete token bucket: it holds two tokens, refills one token every 250 milliseconds, and starts full. Each request consumes a specified number of tokens. If there are not enough tokens, the request is rejected immediately; the bucket does not queue requests. The refill schedule starts at initialization, and consuming tokens does not reset it.
This model fits situations where you want to limit short bursts while allowing a few tasks to run back-to-back after an idle period. It does not fit a requirement to stay below a fixed request count within every sliding window. The two models behave differently at their boundaries.
Client-side rate limiting only controls the pace of requests issued by that client. It cannot replace server-side quota checks. Restarting the process also refills the bucket, so this implementation does not establish rate limiting across devices or processes.
Time is represented as monotonically increasing integer milliseconds, not calendar time. The implementation below rejects timestamps that move backward so that mistakes in test fixtures cannot silently alter the state.
Implement a core with injectable time
Save the following code as TokenBucketChecks.swift. The core does not access the network, wait on threads, or depend on the application lifecycle. Capacity and interval must both be greater than zero; that is the construction contract. Validate external configuration before creating an instance.
import Dispatch
import XCTest
struct TokenBucket {
let capacity: UInt64
let interval: UInt64
private(set) var tokens: UInt64
private var last: UInt64
init(capacity: UInt64, interval: UInt64, now: UInt64) {
precondition(capacity > 0 && interval > 0)
self.capacity = capacity
self.interval = interval
self.tokens = capacity
self.last = now
}
mutating func take(_ cost: UInt64 = 1, at now: UInt64) -> Bool {
guard now >= last else { return false }
let steps = (now - last) / interval
if steps > 0 {
let room = capacity - tokens
if steps >= room {
tokens = capacity
} else {
tokens += steps
}
last += steps * interval
}
guard cost > 0 && cost <= tokens else { return false }
tokens -= cost
return true
}
}
The code checks the available capacity before adding tokens, avoiding the overflow that a direct addition could cause after a long idle period. Since steps * interval cannot exceed now - last, advancing the refill timestamp cannot take it beyond the supplied current time either.
Once the balance reaches capacity, no extra tokens are stored, but the refill schedule retains its phase. For example, consuming a token at 249 milliseconds still allows a refill at 250 milliseconds. This is an explicit modeling choice, not a guarantee of an exact continuous average rate.
Replace real waits with boundary tests
Append the following tests to the same file. The first test checks burst capacity and refill boundaries; the second checks long idle periods and invalid inputs. Each assertion uses an explicit timestamp with a clear rationale, independent of how busy the cloud machine happens to be.
final class BucketTests: XCTestCase {
func testBurstAndRefill() {
var bucket = TokenBucket(capacity: 2, interval: 250, now: 0)
XCTAssertTrue(bucket.take(at: 0))
XCTAssertTrue(bucket.take(at: 0))
XCTAssertFalse(bucket.take(at: 249))
XCTAssertTrue(bucket.take(at: 250))
XCTAssertTrue(bucket.take(at: 749))
XCTAssertTrue(bucket.take(at: 750))
XCTAssertFalse(bucket.take(at: 750))
}
func testIdleCapAndInvalidInputs() {
var bucket = TokenBucket(capacity: 2, interval: 250, now: 0)
XCTAssertTrue(bucket.take(2, at: 0))
XCTAssertTrue(bucket.take(at: 10_000))
XCTAssertTrue(bucket.take(at: 10_000))
XCTAssertFalse(bucket.take(at: 10_000))
let before = bucket.tokens
XCTAssertFalse(bucket.take(at: 9_999))
XCTAssertEqual(bucket.tokens, before)
XCTAssertFalse(bucket.take(0, at: 10_000))
XCTAssertFalse(bucket.take(3, at: 10_000))
}
}
XCTMain([
testCase([
("testBurstAndRefill", BucketTests.testBurstAndRefill),
("testIdleCapAndInvalidInputs", BucketTests.testIdleCapAndInvalidInputs)
])
])
Run it with the developer tools from a full Xcode installation:
xcrun swift TokenBucketChecks.swift
Use the command's exit code as the pass/fail result, rather than looking for a particular word in the logs. This script validates the shared Swift algorithm. When moving it into an iOS test target, keep the test methods and remove the final XCTMain call so that the test runner can discover the cases.
Additional cases should cover a capacity of one, consuming the full capacity in a single request, a nonzero initialization timestamp, and inputs close to UInt64.max. Do not make a failing test pass by allowing “a few milliseconds of tolerance.” That would turn a deterministic test back into a timing test.
Connect a monotonic clock and a serialized entry point
Production code can read milliseconds from DispatchTime.now().uptimeNanoseconds / 1_000_000. Initialization and subsequent requests must use the same time source. Do not mix in server time, wall-clock time, or a relative counter measured from app launch.
When multiple tasks share a bucket, put the clock read, refill, and token deduction in the same actor method, with no await inside it. If you use a lock instead, read the time only after acquiring the lock. Otherwise, a call that reads the clock first may enter the critical section later and be rejected for moving backward in time.
Define suspension and recreation rules explicitly
This article does not guarantee that tokens accumulate during system sleep. If your product requires sleep time to count, choose a clock with those semantics and test it separately. Recreating the bucket after the app terminates restores its full capacity. If that is unacceptable, you need an additional persistence protocol; saving the token balance alone is not enough.
Turn failures into actionable conclusions
Before submitting, check each requirement: the initial burst is exactly equal to capacity; a request one millisecond before refill is rejected; a request at the boundary is allowed; multiple elapsed intervals cannot push the balance above capacity; zero-cost requests and requests exceeding capacity are rejected; and backward timestamps leave the state unchanged.
If failures appear only after integration into the app, first check whether multiple buckets are being created, whether the instance is recreated before every request, and whether retries bypass the shared entry point. If the tests pass but requests are still too frequent, revisit the capacity and interval rather than adding waits to hide the discrepancy.
Finally, record algorithm test results separately from integration test results. The former answers “Are the state transitions correct?” The latter answers “Do all requests actually pass through the same rate-limiting entry point?” Keeping those questions separate makes remote tests reproducible and the next regression easier to diagnose.
Frequently asked questions
Why avoid sleep in refill tests?
Sleeping does not guarantee that a thread resumes at an exact instant. Injected integer timestamps let tests cover one millisecond before a refill, the boundary itself, and multiple elapsed intervals.
Is the token bucket safe for concurrent callers?
Not by itself. Read the clock, refill, and consume within one serialized operation protected by the same actor or lock.
Let your project decide which Mac to rent
Need native builds or simulator testing? Rent an Apple Silicon dedicated physical Mac to validate your project. If you develop full-time and work from one location, buying may also be worth comparing. Rent by the day for flexibility, then consider a monthly or quarterly plan for ongoing use.
Rent a Remote Mac