❯ehsan.blog
~/blog/redis-rate-limiter-keys-that-never-expire — zsh
❯cat redis-rate-limiter-keys-that-never-expire.md

Your Redis rate limiter can leave keys that never expire

·9 min read

Your Redis rate limiter can leave keys that never expire — article card for a post by Ehsan Shahid

I added a Redis-backed rate limiter to nextjs-logger last week. It is the same twelve lines you have probably written yourself: INCR a key, set a TTL on it, reject the caller when the count goes past the limit.

Then I wrote a test for the case nobody tests. What if the first command works and the second one does not?

The answer surprised me. The key stays in Redis with no expiry, and the code never tries to fix it again. Not on the next request. Not on the request after that. The key is there until somebody deletes it by hand.

Here is how I found it, and how worried you should actually be.

Why a logging endpoint needs a limit at all

Skip this part if you already know why. It is the setting, not the bug.

nextjs-logger takes console.log calls from a browser and prints them in your server terminal. To do that, the page has to POST somewhere. That POST target is a normal public URL. It does not know the difference between my code and yours.

There is a signed session token on every request. People assume that is the protection. It is not. The token is minted on the server and sits in the page HTML, because the browser needs to prove it loaded a real page and the browser cannot hold the signing secret. So anyone who opens the page can read the token out of the HTML and replay it with curl.

The token answers one question: is this caller allowed at all? It says nothing about how many times. Those are different questions, and the second one is the one that fills your disk.

A counter in memory handles the small version of this, and I wrote about that shape before in in-memory rate limiting on a serverless function. But memory is per instance. Run five warm instances and your “120 requests per 10 seconds” cap is really 600, and the platform picks the number of instances based on the traffic you are trying to limit. To cap the whole fleet, the counter has to live somewhere shared.

That is the Redis part. That is where the bug lives.

The two commands

The whole check is short:

ts
const window = Math.floor(Date.now() / policy.windowMs)
const redisKey = `${prefix}${key}:${window}`

const count = await client.incr(redisKey)

if (count === 1) {
  await client.pexpire(redisKey, policy.windowMs)
}

if (count > policy.limit) {
  return {
    allowed: false,
    retryAfterSeconds: await resetSeconds(client, redisKey, policy),
  }
}
return { allowed: true, retryAfterSeconds: 0 }

Two things are doing real work here.

The time window is baked into the key name. window is a number that changes every windowMs milliseconds. So every window gets a brand new key that dies on its own. There is no “reset the counter” step to race on, which is the part people usually get wrong. A plain INCR on a fresh key is already correct.

Only the first call sets the TTL. That count === 1 guard is not an optimization. If you called PEXPIRE on every request, a busy client would push the expiry forward forever and the window would never reset. The guard is right.

It is also exactly what makes the bug possible.

The failure nobody tests

INCR and PEXPIRE are two separate network calls. Redis has no transaction wrapped around them here. So there is a moment, small but real, where the first one has landed and the second one has not.

If the connection drops in that moment, this is the state you are left with:

  • The key exists. INCR created it.
  • The key has no TTL. PEXPIRE never ran.
  • count is now 1, so on the next request count will be 2, and the count === 1 branch never runs again.

Nothing retries the TTL. The guard that makes the healthy path correct is the same guard that makes the broken path permanent.

I did not want to guess at this, so I built a fake Redis that records which keys got a TTL, made PEXPIRE throw exactly once, and checked what was left behind.

ts
function fakeRedis(pexpireFailsOnce: boolean) {
  const store = new Map<string, number>()
  const ttls = new Map<string, number>()
  let failed = false
  return {
    store, ttls,
    client: {
      async incr(key: string) {
        const n = (store.get(key) ?? 0) + 1
        store.set(key, n)
        return n
      },
      async pexpire(key: string, ms: number) {
        if (pexpireFailsOnce && !failed) { failed = true; throw new Error('net blip') }
        ttls.set(key, ms)
        return 1
      },
    },
  }
}

One of the four tests, with a limit of 3 per window:

ts
it('subsequent calls in the SAME window never retry the TTL', async () => {
  const r = fakeRedis(true)
  const check = createRedisRateLimiter(r.client, { onError: () => {} })

  for (let i = 0; i < 5; i++) await check('ip1', policy)

  expect(r.ttls.size).toBe(0)          // no TTL, ever

  const [key] = [...r.store.keys()]
  expect(r.store.get(key)).toBe(5)     // but the count kept counting
})

All four passed. Here is everything they checked:

What I checkedResult
Request is still allowed when PEXPIRE throwsallowed
Key exists after that requestyes
TTL set on itnone
TTL retried across the next 4 requestsnever
Limit still enforced inside the windowyes — [true, true, true, false, false]
Healthy path, 5 requestsexactly 1 TTL set

That last row matters. The healthy path is fine. One TTL per key, as designed.

So how bad is it really

I want to be honest about the size of this, because “Redis key leak” sounds worse than it is.

The limiter keeps working. That fifth row is the one that matters: with a dead TTL, the counter still counted, and requests 4 and 5 were still rejected. The cap held.

And the stranded key cannot poison a later window. The window number comes from Math.floor(Date.now() / windowMs), which only goes up. Once the clock moves on, the next request builds a different key name. The orphan just sits there at whatever count it reached.

So the real cost is one abandoned key per partial failure, sitting in Redis forever. Not a wrong answer. Not a broken cap. Just garbage that accumulates.

Two things decide whether that ever hurts you:

  1. How often the gap actually happens. It needs a failure that lands between two calls that are microseconds apart. On a healthy network that is rare.
  2. Whether your Redis evicts. Most managed Redis, including Upstash, runs with a maxmemory-policy that throws out old keys under pressure. If yours is set to noeviction, nothing cleans these up and they only grow.

If you run redis-cli --scan --pattern 'logger:rl:*' and see keys much older than your window, you are looking at them. TTL <key> returning -1 confirms it: the key exists and has no expiry.

The fix, and why I did not reach for it first

The clean answer is to make the two commands one command, so there is no gap:

ts
const count = await client.eval(
  `local n = redis.call('INCR', KEYS[1])
   if n == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
   return n`,
  1, redisKey, String(policy.windowMs)
)

Redis runs a script as one unit, so INCR and PEXPIRE either both happen or neither does. Upstash supports EVAL over its REST API too, so this works on the edge. The cost is that your client interface now needs an eval method, where before it needed only incr and pexpire — which is why ioredis, node-redis and Upstash could all drop in without an adapter.

The cheaper patch, if you do not want a script: set the TTL whenever the count is small, not only when it is exactly 1.

ts
if (count <= 3) {
  await client.pexpire(redisKey, policy.windowMs)
}

Now a single dropped PEXPIRE gets a second and third chance. But I want to be precise about the price, because I checked it rather than assumed it. Each PEXPIRE resets the expiry from now, so requests 2 and 3 do push the window forward. I ran it: three requests at 0ms, 40ms and 90ms into a 1000ms window left the key expiring at 1090ms instead of 1000ms.

The important part is that the drift is bounded. I then fired 91 requests across the window, and the expiry still landed at 1020ms — because after the third one, the branch stops running. So you are trading a fixed, tiny stretch of the window for a PEXPIRE that gets retried. On the current count === 1 code the same 91 requests left it at exactly 1000ms, no drift at all.

I shipped neither at first. The reason is boring and I think it is the right one: I was building a cap for a logging relay, and a handful of orphaned keys is a smaller problem than the one I was there to solve. The EVAL version is what I would write for anything where the counter is the security boundary. Knowing which of those you are building is most of the decision.

The other choice this code makes: fail open

There is a try/catch around the whole check, and every error path returns allowed: true.

That is deliberate, and it is the opposite of what you want for a payment API.

Think about what failing closed means for a logging endpoint. Redis has a bad minute. During that minute you block every browser log. You have now deleted your own visibility at the exact moment something is wrong with your infrastructure — and a Redis blip is far more likely than an actual attacker. You would be trading a common, harmless event for a blackout of the tool you use to debug the uncommon one.

So errors fall through to allow, and the in-memory counter stays as the floor. The one thing you must not do is let that be quiet. A rate limiter that silently stops limiting is worse than no rate limiter, because you believe you have one. The onError handler prints a single warning and then suppresses the rest, which is the same reasoning I used when a dead Redis cache was flooding the logs.

What I took away

The count === 1 guard is correct. I would write it again. What I missed was that a guard which runs once is also a guard that retries never, and in a two-command sequence with no transaction, “runs once” and “runs zero times” are one dropped packet apart.

The general shape, if you want one sentence to carry out of here: whenever you set up state in a branch that only fires on the first call, ask what happens if that exact call is the one that fails. Usually nothing catches it later, because the condition that would have caught it is already false.

I only found it because I wrote a test for a failure I did not expect to matter. That is the cheapest debugging I did all week.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.