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.
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:
@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: https://github.com/steveklabnik/request_store
Since Thread is a Ruby-interpreter thing, and not a Rails thing, this is not a bug, so I'm closing.
Conditionalize thread local cleaning. Possible perf degradation fix