search
HomeDatabaseRedisSeveral ways to implement speed limiter in redis

Several ways to implement speed limiter in redis

redis Several ways to implement the speed limiter.

GET INCR EXPIRE

Get the current value of key first. If it does not exceed the limit, execute INCR and increment it by 1. If key does not exist, use the transaction of redis to initialize key and Expiration.

(Recommended: redis video tutorial)

Pseudo code:

count = redis.GET(key)
if redis return nil {
  redis.MULTI
  	redis.INCR(key)
  	redis.EXPIRE(key, expire_time)
  redis.EXEC
  count = 1
}
if count > limit {
  return 超出限制
} else {
  redis.INCR(key)
}

Problems under high concurrency:

If 10 at the same time If a concurrent program executes GET and returns nil, then these 10 concurrent programs will execute redis transactions to increase key by one, but the count value of each program is 1. If the value set by limit is less than 10, then the program that is actually executed will The limit has been exceeded. If redis is checked again after executing the transaction and assigned to count, then each program may return 10, so no program can continue to execute.

When the key already exists, the logic of GET first and then INCR may also cause the number of actually executed programs to exceed the limit.

INCR EXPIRE

First INCR, if the value is 1, it means that the key has just been set, then execute EXPIRE

Pseudo code:

count = redis.INCR(key)
if count == 1 {
  redis.EXPIRE(key, expire_time)
}
if count > limit {
  return 超出限制
}

Use with caution

If the program hangs after INCR and EXPIRE is not executed, then the key will have no expiration time. The specific impact depends on the needs.

lua script

local current
current = redis.call("incr",KEYS[1])
if tonumber(current) == 1 then
    redis.call("expire",KEYS[1],1)
end

For more redis knowledge, please pay attention to the redis introductory tutorial column.

The above is the detailed content of Several ways to implement speed limiter in redis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:oschina. If there is any infringement, please contact admin@php.cn delete
Redis vs databases: performance comparisonsRedis vs databases: performance comparisonsMay 14, 2025 am 12:11 AM

Redisoutperformstraditionaldatabasesinspeedforread/writeoperationsduetoitsin-memorynature,whiletraditionaldatabasesexcelincomplexqueriesanddataintegrity.1)Redisisidealforreal-timeanalyticsandcaching,offeringphenomenalperformance.2)Traditionaldatabase

When Should I Use Redis Instead of a Traditional Database?When Should I Use Redis Instead of a Traditional Database?May 13, 2025 pm 04:01 PM

UseRedisinsteadofatraditionaldatabasewhenyourapplicationrequiresspeedandreal-timedataprocessing,suchasforcaching,sessionmanagement,orreal-timeanalytics.Redisexcelsin:1)Caching,reducingloadonprimarydatabases;2)Sessionmanagement,simplifyingdatahandling

Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools