Letting people use a web app before creating an account removes a lot of friction. It also turns a simple rate limit into a small state-management problem: how do you enforce a daily free quota when the same person can upload a file while signed out, sign in ten minutes later, log out again, or switch browsers?

I ran into this on Sorirok, a small Next.js App Router app that turns Korean audio recordings (meetings, interviews, phone calls) into Word, TXT, and SRT transcripts. Everyone gets the same free allowance: 3 files per day (resetting on Korean time), up to 1 hour each.

Early on, I had different free limits for signed-out and signed-in users. That was a mistake. People got confused when their remaining quota changed after logging in, and it added extra branches everywhere. Making the free tier identical for everyone simplified the product—and left one clear problem: counting it fairly across anonymous and signed-in sessions.

Why one Redis key isn't enough

Tracking a daily limit with a single identifier breaks in predictable ways:

  • Account ID only doesn't work before sign-in, and logging out looks like a reset.
  • Browser cookie only resets as soon as someone clears cookies.
  • IP address only hurts normal users. Korean mobile carriers and offices routinely put many people behind one IP, so a 3-per-IP limit blocks strangers who haven't used the app at all.

Instead, I store counters in Upstash Redis under three key patterns, all scoped to the current Korean-time date (YYYY-MM-DD):

  • free:<day>:u:<userId> — account count, when signed in.
  • free:<day>:a:<anonCookie> — browser count, via an anonymous cookie that signed-in users also get.
  • free:<day>:ip:<ip> — IP count, used only for signed-out visitors, with a generous ceiling so shared carrier or office IPs aren't immediately blocked.

Keeping the anonymous cookie active after sign-in is what makes the rest work. When a signed-in user uses a free upload, both the account key and the browser key increment, so logging out doesn't give them a fresh quota.

"Used today" is max(account count, browser count), and a signed-out visitor whose IP counter has hit its limit is treated as exhausted:

function quotaKeys(day: string, opts: { userId?: string; anonId: string; ip?: string }) { return { user: opts.userId ? `free:${day}:u:${opts.userId}` : null, anon: `free:${day}:a:${opts.anonId}`, ip: !opts.userId && opts.ip ? `free:${day}:ip:${opts.ip}` : null, }; } async function getQuotaState(keys: ReturnType<typeof quotaKeys>) { const [userCount, anonCount, ipCount] = await Promise.all([ keys.user ? redis.get<number>(keys.user) : 0, redis.get<number>(keys.anon), keys.ip ? redis.get<number>(keys.ip) : 0, ]); const usedToday = Math.max(userCount ?? 0, anonCount ?? 0); const ipExhausted = keys.ip !== null && (ipCount ?? 0) >= FREE_DAILY_IP_LIMIT; return { usedToday, exhausted: usedToday >= FREE_DAILY_FILES || ipExhausted }; } 

Because signed-in requests skip the IP key, someone on a crowded office network who hits the signed-out IP cap can still use their quota by signing in.

Reserve first, check second

The naive flow—GET the counter, check < 3, create the job, then INCR—has an obvious race. Two tabs or a double-click can both read 2 and slip through at the same time.

To close that window, the route increments first and checks the result afterwards. When INCR returns 1 (the key was just created), we set EXPIRE to the seconds left in the Korean day plus 3600. Because keys include the date, keeping them around for an extra hour past midnight is harmless and avoids boundary edge cases.

If any incremented key exceeds its limit—or if creating the job fails—we DECR every key we touched to release the slot, and return 402 on quota exhaustion:

async function incrWithTtl(key: string, ttlSeconds: number) { const value = await redis.incr(key); if (value === 1) await redis.expire(key, ttlSeconds); return value; } async function reserveFreeSlot( keys: ReturnType<typeof quotaKeys>, secondsLeftInDay: number, ) { const ttl = secondsLeftInDay + 3600; const checks = [{ key: keys.anon, limit: FREE_DAILY_FILES }]; if (keys.user) checks.push({ key: keys.user, limit: FREE_DAILY_FILES }); if (keys.ip) checks.push({ key: keys.ip, limit: FREE_DAILY_IP_LIMIT }); const results = await Promise.all( checks.map(async (c) => ({ ...c, value: await incrWithTtl(c.key, ttl) })), ); const release = () => Promise.all(results.map((r) => redis.decr(r.key))); if (results.some((r) => r.value > r.limit)) { await release(); return { ok: false as const }; } return { ok: true as const, release }; } 

In the route handler, release() also runs in the catch block so a failed job creation doesn't burn a user's daily slot:

const slot = await reserveFreeSlot(keys, secondsLeftInKstDay()); if (!slot.ok) { return NextResponse.json({ error: "Daily free limit reached" }, { status: 402 }); } try { return NextResponse.json(await createTranscriptionJob(payload)); } catch (err) { await slot.release(); throw err; } 

Crossing the login boundary

Allowing anonymous usage means login has to merge two things from the browser into the account: today's counter and any files uploaded before sign-in.

Merging today's quota

If a visitor uses 2 files while signed out and then logs in, we read today's account and browser keys and set the account key to max(account, browser) with a TTL of end-of-day plus 1 hour:

async function mergeQuotaOnLogin( userId: string, anonId: string, day: string, secondsLeftInDay: number, ) { const userKey = `free:${day}:u:${userId}`; const anonKey = `free:${day}:a:${anonId}`; const [userCount, anonCount] = await Promise.all([ redis.get<number>(userKey), redis.get<number>(anonKey), ]); const merged = Math.max(userCount ?? 0, anonCount ?? 0); if (merged > 0) { await redis.set(userKey, merged, { ex: secondsLeftInDay + 3600 }); } } 

Together with the persistent anonymous cookie, neither shortcut works: logging out keeps the browser count, and logging into another browser picks up the merged account count.

Retrying failed upload claims

Files uploaded before sign-in are claimed to the account at login. If that claim fails, I don't retry it on every request; instead, it retries at most once a day when the user opens their transcript list. A Redis SET NX lock with a 24-hour expiry gates it, and polling or search requests skip it entirely:

async function maybeRetryClaim(userId: string, anonId: string, skip: boolean) { if (skip) return; // polling and search requests skip retries const acquired = await redis.set(`claim-retry:${userId}:${anonId}`, "1", { nx: true, ex: 86400, }); if (!acquired) return; await claimAnonymousUploads(userId, anonId); } 

What Redis can't enforce: client-reported duration

Counting uploads only handles "3 files a day." The browser uploads audio straight to object storage via a presigned URL; the Next.js server only issues the URL, hears back when the upload finishes, and creates the job—it never reads the file body.

That means the audio duration used for quota checks and pricing comes from the browser, and any client-reported number can be faked. Rather than downloading every file on the server to inspect it, paid jobs cap how much audio gets processed based on what was charged, plus a small margin:

const maxDurationSeconds = Math.min( paidMaxSeconds, Math.ceil(chargeSeconds * 1.5) + 60, ); 

Lying about the file length just produces a truncated transcript, without giving up direct uploads.

Closing notes

None of this stops someone determined to rotate cookies and IPs, and that's fine. For a small app, the goal is making normal usage smooth while making casual resets pointless. Using the same free limit before and after login, reserving slots with INCR before checking, and keeping the anonymous cookie around after sign-in got me most of the way there with very little code.