Skip to content

Commit ff0a7ad

Browse files
committed
Run ICNRBY + EXPIRE in a single atomic transaction
1 parent 8e2fdd6 commit ff0a7ad

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

httprateredis.go

+11-11
Original file line numberDiff line numberDiff line change
@@ -102,20 +102,20 @@ func (c *redisCounter) IncrementBy(key string, currentWindow time.Time, amount i
102102

103103
hkey := c.limitCounterKey(key, currentWindow)
104104

105-
cmd := conn.Do(ctx, "INCRBY", hkey, amount)
106-
if cmd == nil {
107-
return fmt.Errorf("httprateredis: redis incr failed")
108-
}
109-
if err := cmd.Err(); err != nil {
110-
return err
105+
pipe := conn.TxPipeline()
106+
incrCmd := pipe.IncrBy(ctx, hkey, int64(amount))
107+
expireCmd := pipe.Expire(ctx, hkey, c.windowLength*3)
108+
_, err := pipe.Exec(ctx)
109+
if err != nil {
110+
return fmt.Errorf("httprateredis: redis transaction failed: %w", err)
111111
}
112112

113-
cmd = conn.Do(ctx, "EXPIRE", hkey, c.windowLength.Seconds()*3)
114-
if cmd == nil {
115-
return fmt.Errorf("httprateredis: redis expire failed")
113+
if err := incrCmd.Err(); err != nil {
114+
return fmt.Errorf("httprateredis: redis incr failed: %w", err)
116115
}
117-
if err := cmd.Err(); err != nil {
118-
return err
116+
117+
if err := expireCmd.Err(); err != nil {
118+
return fmt.Errorf("httprateredis: redis expire failed: %w", err)
119119
}
120120

121121
return nil

0 commit comments

Comments
 (0)