ruby
32 lines · 7 steps
A thread-safe throttle in Ruby
A Throttle class that rate-limits actions per key using a monotonic clock and a mutex for safe concurrent access.
Explained by
highlit
1class Throttle
2 def initialize(interval)
3 @interval = interval
4 @mutex = Mutex.new
5 @last_called = {}
6 end
7
8 def call(key = :default)
9 now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
10
11 @mutex.synchronize do
12 last = @last_called[key]
13 return false if last && now - last < @interval
14 @last_called[key] = now
15 end
16
17 yield
18 true
19 end
20
21 def remaining(key = :default)
22 last = @mutex.synchronize { @last_called[key] }
23 return 0.0 unless last
24
25 elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - last
26 [@interval - elapsed, 0.0].max
27 end
28
29 def reset(key = :default)
30 @mutex.synchronize { @last_called.delete(key) }
31 end
32end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A monotonic clock avoids the bugs that wall-clock time introduces when the system clock jumps.
- 2Guarding shared state with a mutex keeps the check-and-update sequence atomic across threads.
- 3Keying timestamps by a value lets one throttle independently rate-limit many distinct actions.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-thread-safe-throttle-in-ruby-explained-ruby-f0fd/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.