Rate limiting is an important mechanism for controlling resource utilization and maintaining quality of service. Crystal elegantly supports rate limiting with fibers, channels, and timers.
Running our program we see the first batch of requests handled once every ~200 milliseconds as desired.
For the second batch of requests we serve the first 3 immediately because of the burstable rate limiting, then serve the remaining 2 with ~200ms delays each.
In this Crystal version, we use Channels to implement the rate limiting mechanism. The spawn keyword is used to create new fibers (lightweight threads) for handling the timing operations. The Time.utc method is used to get the current time, which is equivalent to time.Now() in Go.
The overall structure and logic of the program remain the same as the original Go version, demonstrating how similar concepts can be expressed in Crystal’s syntax.