Counting a daily free quota in Redis without forcing sign-in first
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…
Allowing users to access a web application before creating an account eliminates much of the initial friction. However, this approach turns a straightforward rate limit into a small state management problem. Specifically, it becomes challenging to enforce a daily free quota when the same individual can upload files while signed out, sign in later, or switch browsers.
One web application faced this challenge: Sorirok, a Next.js App Router app that converts Korean audio recordings into various formats. The app sets a universal daily allowance of three files, each no longer than one hour, regardless of whether users are signed in or out. Initially, the app had separate free limits for signed-out and signed-in users, but this led to confusion and added complexity.
To address this, the developers designed a single Redis key system that tracks the daily limit fairly across anonymous and signed-in sessions. They store counters in Upstash Redis, scoped to the current Korean time date (YYYY-MM-DD), under three key patterns: free:day:u:userId for account count when signed in, free:day:a:anonCookie for browser count using an anonymous cookie also received by signed-in users, and free:day:ip:ip for IP count, used only for signed-out visitors with a higher limit to avoid immediate blocking of users sharing IP addresses.
The anonymous cookie remains active even after sign-in, ensuring consistency in quota tracking. When a signed-in user uses a free upload, both the account key and browser key are incremented, preventing them from starting fresh after logging out. The system determines the "used today" quota by taking the maximum of the account count and browser count for signed-in users.
For unsigned visitors, if the IP counter hits its limit, they are considered exhausted. The code snippet provided outlines the logic for retrieving the quota state and incrementing the quota with a time-to-live (TTL) value, ensuring that keys are correctly managed and preventing race conditions.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to