0 day streak
go / intermediate
Snippet

Rate Limiting Concurrent Operations with time.Ticker

In Go, rate limiting can be implemented using time.Ticker. A ticker sends a signal over its channel C at a regular interval. By reading from ticker.C before handling each request, we block the loop until the next tick, ensuring that requests are processed at a steady, controlled rate without overloading downstream services.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
import (
"fmt"
"time"
)
func processRequests(requests <-chan int, rate time.Duration) {
ticker := time.NewTicker(rate)
defer ticker.Stop()
for req := range requests {
<-ticker.C
fmt.Printf("Processed request %d at %s\n", req, time.Now().Format("15:04:05"))
}
}
Breakdown
1
ticker := time.NewTicker(rate)
Creates a new ticker that delivers channel ticks at the specified rate duration.
2
defer ticker.Stop()
Ensures the ticker resources are cleaned up when the function returns to prevent resource leaks.
3
<-ticker.C
Blocks the execution loop until a tick is received from the ticker channel, enforcing the delay.