Satchel
Satchel

Reputation: 16724

How do I use Ruby to do a certain number of actions per second?

I want to test a rate-limiting app with Ruby where I define different behavior based on the number of requests per second.

For example, if I see 300 request per second or more, I want it to respond with a block.

But how would I test this by generating 300 requests per second in Ruby? I understand there are hard limitations based on CPU for example, but if I kept the number well below that limitation, how would I still send something that both exceeds the threshold and stays below?

Just looping N-times doesn't guarantee me the throughput.

Upvotes: 4

Views: 875

Answers (2)

Alex D
Alex D

Reputation: 30445

How about a minimal homebrew solution:

OPS_PER_SECOND = 300
count = 0
duration = 10
start = Time.now

while true
  elapsed = Time.now - start
  break if elapsed >= duration
  delay = (count - (elapsed / OPS_PER_SECOND)) / OPS_PER_SECOND
  sleep(delay) if delay > 0
  do_request
  count += 1
end

Upvotes: 1

tadman
tadman

Reputation: 211540

The quick and dirty way is to spin up 300 threads that each do one request per second. The more elegant way is to use something like Eventmachine to create requests at the required rate. With the right non-blocking HTTP library it can easily generate that level of activity.

You also might try these tools:

  • ab the Apache benchmarking tool, common many systems. It's very good at abusing your system.
  • Seige for load testing.

Upvotes: 3

Related Questions