title: Rails + Nginx: HTTP 499 errors and clients repeating POSTs
body: <p>So, I'm investigating MySQL deadlock exceptions on our Rails/Unicorn/Nginx app. What I've found is that sometimes, we'll see a storm of requests that get a 499 status code from one client. From <a href="http://forum.nginx.org/read.php?2,213789,213793#msg-213793" rel="nofollow noreferrer">this post</a>, it looks like nginx returns 499 when the client closes the connection unexpectedly or, um, something. I'm not quite clear on whether the client actually sees the status code or not; I can't replicate this locally.</p>
  
  <p>From the nginx logs, it looks like in these requests, we wind up writing 0 bytes to the client. In my Rails logs, there's nothing remarkable about the requests; they're finishing in normal amounts of time (40-120 ms) and returning a 302 redirect.</p>
  
  <p>So, whatever, right? But! What makes this bad is that the client appears to be interpreting whatever it's seeing (or not seeing) as an invitation to try its request again. Even if it's a POST. And my Rails app is happily handling those requests and creating duplicate entries in the database. Sometimes it creates quite a lot of records — in one case, we had a client repeat a request some 6500 times over about ten minutes. That's... suboptimal.</p>
  
  <p>I'm trying to figure out what to do. What I'd really like is to fix whatever interaction I'm seeing with nginx, but I'm not sure how — if the client is closing the connection before it gets data, I can't control what it's gonna do.</p>
  
  <p>An alternative (which feels like a horrible hack) is to do something like include a unique key (say, from a <a href="http://www.microshell.com/database/mysql/emulating-nextval-function-to-get-sequence-in-mysql/" rel="nofollow noreferrer">sequence</a>) in a hidden form and have a unique index on the corresponding database column. But there are millions of rows on this table so screwing around with its schema is not something I want to do lightly.</p>
  
  <p>In case it matters, the requests are being done via HTTPS. It looks like it comes most commonly from a small subset of our clients.</p>
  
  <p>Has anyone else seen this (other than <a href="https://stackoverflow.com/questions/9914115/what-could-cause-duplicate-records-to-be-created-by-rails/9915140#9915140">this post</a>)? Am I totally mad? Can anyone think of an elegant solution?</p>