Skip to content


Subversion checkout URL

You can clone with
Download ZIP


Thread.current values are being kept between requests #8517

elado opened this Issue · 5 comments

5 participants


Under servers like thin and `unicorn, threads are managed in a way that the Thread.current keeps its values between requests, unless cleared.

This code in a controller:

before = Thread.current[:x]
Thread.current[:x] = 1
render text: [ before, Thread.current[:x]  ].inspect

when executed twice (even from different sessions), will print nil, 1, and then 1, 1.

I saw that when Rails used Thread.current (e.g. in IdentityMap, Explain) it cleared the value before the request and restored it. If this is necessary all the time, how about clearing Thread.current between requests with a middleware as a part of Rails? Or have some kind of per-request storage for Rails.


@steveklabnik steveklabnik referenced this issue in drapergem/draper

Use of Thread.current and ViewContext #390


I agree with @elado that it should be the middleware's responsibility to create and destroy a per-request storage object around each request.

This storage object might end up being a thin wrapper around Thread.current, but having it abstracted from any specific threading code will decouple the code that uses it from knowledge of Rails' threading model and make tests running in parallel less susceptible to cross contamination.


The way to got about it without breaking stuff is:

  • Clear that variable before request. Clearing it after request is difficult to do cleanly, because exceptions might result in after filter never being triggered
  • Clearing all the variables is a bit dangerous, because Thread.current may be used for keeping permanent per-thread data, such as stats, profiling information, separate log outputs per threads, etc... For a typical Rails application this is probably not an issue, but clearing Thread.current will cause issues when trying to debug local memory leaks and such.

@tenderlove is always interested about thread safety issues, so calling him in on this one, too.


Automatically nuking all of the Thread.current values at the end or beginning of the request should be out of question.

If Rails' usage of Thread.current results in bugs, please open a ticket. Otherwise if your code uses Thread.current and doesn't clean up after itself, you should fix your code.


I wrote a gem:

Since Thread is a Ruby-interpreter thing, and not a Rails thing, this is not a bug, so I'm closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.