david0116
david0116

Reputation: 103

Ajax request speed issue

I want to prevent from user sending requests from ajax too fast. I wrote a validation in controller as bellow.

def before_action
    if session[:expires_at].nil?
       logger.info "Operation is legal"
       session[:expires_at] = Time.current + 3.seconds
    elsif Time.current > session[:expires_at].to_time
       logger.info "Operation is legal"
       session[:expires_at] = Time.current + 3.seconds
    else
       logger.info "Error: Operation too fast"
       render json: { msg: "Operation too fast",res: "Err"}
       return
    end
    sleep 2 <-- The issue happends here
end

The sleep 2 seconds means my program excution time. If I remove sleep 2 seconds, everything works fine.The result would like below when I send the requests really fast.

-----------Logs-------------
Operation is legal
Error: Operation too fast
Error: Operation too fast
Error: Operation too fast
Error: Operation too fast
Error: Operation too fast
Operation is legal
Error: Operation too fast
Error: Operation too fast
Error: Operation too fast
----------------------------

But, if the second or more resquests been sended before the first one excutes finished. The result would be unexpected. If I add sleep 2 in the validation code.

-----------Logs-------------
Operation is legal
Operation is legal
Operation is legal
Error: Operation too fast
Error: Operation too fast
Error: Operation too fast
Error: Operation too fast
Operation is legal
Operation is legal
Error: Operation too fast
Error: Operation too fast
----------------------------

I am totally confused for this situation. Would the session value not being saved before the request finished? How should I fix this issue?

Upvotes: 1

Views: 64

Answers (1)

devanand
devanand

Reputation: 5290

it looks like the session variables will be stored later in processing a controller lifecycle? a workaround could be to use redis for this case?

you should find a way to be sure a variable you are using is persistent over more requests in parallel.

Upvotes: 1

Related Questions