Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
refactor: improve Redis increment script logic
- Update the increment script to handle expiration and reset conditions more effectively.
- Introduce parameters for window duration and reset behavior, enhancing script functionality.
  • Loading branch information
mt-ks committed Oct 20, 2025
commit 9b4f83adb478b97610658d27750e24f2db733af2
25 changes: 17 additions & 8 deletions source/scripts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,24 @@
*/
const scripts = {
increment: `
local totalHits = redis.call("INCR", KEYS[1])
local timeToExpire = redis.call("PTTL", KEYS[1])
if timeToExpire < 0 or ARGV[1] == "1"
then
redis.call("PEXPIRE", KEYS[1], tonumber(ARGV[2]))
timeToExpire = tonumber(ARGV[2])
end
local windowMs = tonumber(ARGV[2])
local resetOnChange = ARGV[1] == "1"
return { totalHits, timeToExpire }
local timeToExpire = redis.call("PTTL", KEYS[1])
Comment on lines +10 to +13
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for making these named variables, we should have done that a while ago.

if timeToExpire <= 0 then
redis.call("SET", KEYS[1], 1, "PX", windowMs)
return { 1, windowMs }
end
local totalHits = redis.call("INCR", KEYS[1])
if resetOnChange then
redis.call("PEXPIRE", KEYS[1], windowMs)
timeToExpire = windowMs
end
return { totalHits, timeToExpire }
`
// Ensure that code changes that affect whitespace do not affect
// the script contents.
Expand Down