title: How to implement rate limiting using Redis
body: <p>I use <code>INCR</code> and <code>EXPIRE</code> to implement rate limiting, e.g., 5 requests per minute:</p>
  <pre><code>if EXISTS counter
      count = INCR counter
  else
      EXPIRE counter 60
      count = INCR counter
  
  if count &gt; 5
      print &quot;Exceeded the limit&quot;    
  </code></pre>
  <p>However, 5 requests can be sent at the last second minute one and 5 more requests at the first second of minute two, i.e., 10 requests in two seconds.</p>
  <p>How can this problem be avoided?</p>
  <hr />
  <p>Update: I came up with this list implementation.  Is this a good way to do it?</p>
  <pre><code>times = LLEN counter
  if times &lt; 5
      LPUSH counter now()
  else
      time = LINDEX counter -1
      if now() - time &lt; 60
          print &quot;Exceeded the limit&quot;
      else
          LPUSH counter now()
  LTRIM counter 5
  </code></pre>