SlideShare a Scribd company logo
PRESENTED BY
Protecting Your API with Redis
Jane Paek – Jane@redislabs.com
Solution Architect Manager, Redis Labs
PRESENTED BY
Metering and Rate limiting Uses and Design Elements
Protect and Scale Your Application with Rate Limiting and Metering
1
2
3
Why Redis for Rate Limiting and Metering
Rate Limiting Patterns/ Anti Patterns / Design Considerations
Rate Limiting Demo4
5 Resources
Rate Limiting Webinar January 16th 2020, 9am PST
Redis University FREE classes starting January 21, 2020
PRESENTED BY
Metering … It’s Everywhere...
Pay As You Go Freemium Tiered Pricing
Rate LimitingSecurityTraffic Shaping
PRESENTED BY
Rate Limiting Casualties
Load Balancer
Bad Actors?
Unanticipated Use Cases?
Programmatic Errors?
PRESENTED BY
What Do You Need to Meter and Rate Limit?
Load Balancer
1. who - Method for
determining client
■ API key
■ JWT Token
■ IP address
2. how - Pattern to
measure and limit
resources
3. where - Fast
centralized data store
who how where
PRESENTED BY
Why Redis for Metering and Rate Limiting?
In-Database
Analytics
Fast Data
Ingest
High-Speed
Transactions
1. Scales to handle burst access at millions of ops/sec at
sub ms latency
2. Fast centralized store for resource limit and state
3. Optimized commands to control resources
○ Incr/Decr, Count
4. Granular control of resource lifetime
5. “In database” analytics for leaderboards, ranking,
scoring
6. Flexible data structures to meet various metering
designs
Centralized
Store
PRESENTED BY
Redis Data Structures for Metering and Rate Limiting
Lists
[ A → B → C → D → E ]
Hashes
{ A: “foo”, B: “bar”, C: “baz” }
Bitmaps
0011010101100111001010
Strings
"I'm a Plain Text String!”
Bit field
{23334}{112345569}{766538}
Key
Streams
🡪{id1=time1.seq1(A:“xyz”, B:“cdf”),
d2=time2.seq2(D:“abc”, )}🡪
Hyperloglog
00110101 11001110
Sorted Sets
{ A: 0.1, B: 0.3, C: 100 }
Sets
{ A , B , C , D , E }
Geospatial Indexes
{ A: (51.5, 0.12), B: (32.1, 34.7) }
PRESENTED BY
Counting (How Many)
Redis Commands Used for Metering and Rate Limiting
8
Lists | LLEN key
Set | SCARD key
Sorted Set | ZCARD key
Hash | HLEN key
Hyperloglog | PFCOUNT key
Bitmap |
BITCOUNT key [start end]
EXPIRE key seconds
EXPIREAT key timestamp
PEXPIRE key milliseconds
PEXPIREAT key timestamp
SET key value [EX seconds] [PX milliseconds]
INCR key
INCRBY key increment
HINCRBY key field increment
ZINCRBY key increment member
DECR key
DECRBY key decrement
TTL key
PTTL key
Set Key Expiry
Check Time to Live
Incr/Decr Keys
PRESENTED BY
• A rate limiter is a tool that monitors user requests in a defined time
window
• “Users” can be humans or services
• Many different designs, each with tradeoffs in:
– complexity
– data usage
– granularity
• No one size fits all!
• Consider over-limit behavior
Today we are examining Rate Limiters as used in distributed systems
where a central database (Redis!) is needed.
Rate Limiting Design Considerations
9
PRESENTED BY
Simple Fixed Window Counter Using String
• Defined number of requests per time interval
• single STRING per client: user:<identifier>:<window start time>
• E.g. user:ip-address:start-timestamp
user:127.0.0.1:1573767000
• Redis commands used: SET(EX), INCR, TTL
• Redis in the background, will expire old keys
PRESENTED BY
Fixed Window Example: 5 req/min
PRESENTED BY
Fixed Window Example: 5 req/min
PRESENTED BY
Fixed Window Example: 5 req/min
PRESENTED BY
Fixed Window Example: 5 req/min
* Issue: Between 1:30 to 2:15 we allowed 7 requests within a 1 min window
PRESENTED BY
Sliding Window e.g Max 10 req/minute
15
Previous Minute
Sliding 60 sec window
Current Minute
Rejected
requests
PRESENTED BY
Sliding Window e.g Max 10 req/minute
16
Previous Minute
Sliding 60 sec window
Current Minute
Trimmed
requests
PRESENTED BY
Sliding Window e.g Max 10 req/minute
17
Previous Minute
Sliding 60 sec window
Current Minute
Trimmed
requests
PRESENTED BY
Sliding Window Using Sorted Set
18
• Stores timestamps of all requests in one
Sorted Set per user
• Upon new request:
– Add new request timestamp to user’s ZSET
– e.g. ZADD user_1 15000000 15000000
– ZREMRANGEBYSCORE to remove expired timestamps for window
– ZCARD therefore gives number of requests in current window - if larger than limit
deny request
• Sliding Window is extremely accurate, but can be memory expensive
• Consider trimming sorted set when adding and reading the sorted if split
role
• Make sure to expire and extend the expiry of the key when values are
added
Example Redis Sorted Set:
Key Value(timestamp) Score(timestamp)
user_1 : {1500000000 -> 1500000000,
1510000000 -> 1510000000,
....
1576525629 -> 1576525629}
PRESENTED BY
Token Bucket Using Hash
• For each unique user, store in a hash:
– Last request’s timestamp
– Count of available “tokens”
• Upon new request:
– Fetch hash (HGETALL)
– Refill tokens based on refill rate using last timestamp as reference (HSET)
– Update hash with current timestamp and decrement token count (HMSET)
– If no tokens left, deny request
• Challenges:
– Redis operations not atomic (can lead to race conditions in distributed environment)
– Consider using Lua or perform optimistic locking using Watch with Multi-Exec for Check
and Set (CAS) operations
19
Example Redis Hash:
Key TimeStamp AvailTokens
user_1 ->{ts:1576523628, tokens:10}
PRESENTED BY
Rate Limiting Design Anti-Patterns
• Race conditions
– Naive designs may not scale in distributed systems
– e.g. Token Bucket - look for “get, then set” behaviors
• Rate limiting on a super fast API
– Use 10% of total request time for limiting as a rule of thumb
• Unclear user identification
• Granularity vs Resource consumption vs Complexity
• Keeping things local vs distributed
• Using a slow database
– Traditional disk-based databases unable to cope with throughput demands
at scale
20
PRESENTED BY
Drink Limiting Demo
21
PRESENTED BY
Rate Limiting Resources
Rate Limiting Webinar – January 16th 2020, 9am PST. https://bit.ly/2Nl8b9A
Redis University – https://university.redislabs.com/ FREE classes starting January 21, 2020
Articles:
https://www.infoworld.com/article/3230455/how-to-use-redis-for-real-time-metering-
applications.html
Code Samples:
https://github.com/redislabsdemo/RateLimiter - Java
https://github.com/Redislabs-Solution-Architects/RateLimitingExample - Python
22
Thank You!

More Related Content

What's hot (20)

PDF
RedisConf18 - Redis on Flash
Redis Labs
 
PDF
HBaseCon2017 Analyzing cryptocurrencies in real time with hBase, Kafka and St...
HBaseCon
 
PDF
Big Data Day LA 2015 - Always-on Ingestion for Data at Scale by Arvind Prabha...
Data Con LA
 
PDF
RedisConf18 - Introducing RediSearch Aggregations
Redis Labs
 
PPTX
Scaling HDFS at Xiaomi
DataWorks Summit
 
PPTX
HBaseConAsia2018 Track2-3: Bringing MySQL Compatibility to HBase using Databa...
Michael Stack
 
PPTX
RedisConf18 - Redis as a time-series DB
Redis Labs
 
PPTX
HBaseConAsia2018 Track3-7: The application of HBase in New Energy Vehicle Mon...
Michael Stack
 
PPTX
RedisConf18 - Re-architecting Redis-on-Flash with Intel 3DX Point™ Memory
Redis Labs
 
PPTX
SQL, Redis and Kubernetes by Paul Stanton of Windocks - Redis Day Seattle 2020
Redis Labs
 
PPTX
HBaseConAsia2018 Track3-2: HBase at China Telecom
Michael Stack
 
PPTX
Tracking Crime as It Occurs with Apache Phoenix, Apache HBase and Apache NiFi
DataWorks Summit
 
PDF
HBaseConAsia2018 Keynote 2: Recent Development of HBase in Alibaba and Cloud
Michael Stack
 
PPTX
Tailoring Redis Modules For Your Users’ Needs
Redis Labs
 
PDF
Scaling Redis Cluster Deployments for Genome Analysis (featuring LSU) - Terry...
Redis Labs
 
PDF
RedisConf18 - Redis at LINE - 25 Billion Messages Per Day
Redis Labs
 
PDF
Presto @ Uber Hadoop summit2017
Zhenxiao Luo
 
PDF
Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...
HostedbyConfluent
 
PPTX
RedisConf18 - Techniques for Synchronizing In-Memory Caches with Redis
Redis Labs
 
PPTX
In Flux Limiting for a multi-tenant logging service
DataWorks Summit/Hadoop Summit
 
RedisConf18 - Redis on Flash
Redis Labs
 
HBaseCon2017 Analyzing cryptocurrencies in real time with hBase, Kafka and St...
HBaseCon
 
Big Data Day LA 2015 - Always-on Ingestion for Data at Scale by Arvind Prabha...
Data Con LA
 
RedisConf18 - Introducing RediSearch Aggregations
Redis Labs
 
Scaling HDFS at Xiaomi
DataWorks Summit
 
HBaseConAsia2018 Track2-3: Bringing MySQL Compatibility to HBase using Databa...
Michael Stack
 
RedisConf18 - Redis as a time-series DB
Redis Labs
 
HBaseConAsia2018 Track3-7: The application of HBase in New Energy Vehicle Mon...
Michael Stack
 
RedisConf18 - Re-architecting Redis-on-Flash with Intel 3DX Point™ Memory
Redis Labs
 
SQL, Redis and Kubernetes by Paul Stanton of Windocks - Redis Day Seattle 2020
Redis Labs
 
HBaseConAsia2018 Track3-2: HBase at China Telecom
Michael Stack
 
Tracking Crime as It Occurs with Apache Phoenix, Apache HBase and Apache NiFi
DataWorks Summit
 
HBaseConAsia2018 Keynote 2: Recent Development of HBase in Alibaba and Cloud
Michael Stack
 
Tailoring Redis Modules For Your Users’ Needs
Redis Labs
 
Scaling Redis Cluster Deployments for Genome Analysis (featuring LSU) - Terry...
Redis Labs
 
RedisConf18 - Redis at LINE - 25 Billion Messages Per Day
Redis Labs
 
Presto @ Uber Hadoop summit2017
Zhenxiao Luo
 
Streaming Data Lakes using Kafka Connect + Apache Hudi | Vinoth Chandar, Apac...
HostedbyConfluent
 
RedisConf18 - Techniques for Synchronizing In-Memory Caches with Redis
Redis Labs
 
In Flux Limiting for a multi-tenant logging service
DataWorks Summit/Hadoop Summit
 

Similar to Protecting Your API with Redis by Jane Paek - Redis Day Seattle 2020 (20)

PPTX
Rate limiting
Viyaan Jhiingade
 
PDF
mar07-redis.pdf
AnisSalhi3
 
PPTX
Approaches to application request throttling
Maarten Balliauw
 
PDF
REDIS + FastAPI: Implementing a Rate Limiter
techprane
 
PPTX
Redis
Rajesh Kumar
 
PPTX
Approaches for application request throttling - Cloud Developer Days Poland
Maarten Balliauw
 
PDF
An Introduction to Redis for Developers.pdf
Stephen Lorello
 
PDF
Redis Everywhere - Sunshine PHP
Ricard Clau
 
PDF
Mini-Training: Redis
Betclic Everest Group Tech Team
 
PPTX
Rate limits and all about
Alexander Tokarev
 
PPTX
ConFoo Montreal - Approaches for application request throttling
Maarten Balliauw
 
PPTX
Introduction to Redis
Ofer Zelig
 
PDF
Scaling Redis To 1M Ops/Sec: Jane Paek
Redis Labs
 
PDF
Tuga IT 2017 - Redis
Nuno Caneco
 
PPTX
Redis Labcamp
Angelo Simone Scotto
 
PDF
Introduction to Redis
Dvir Volk
 
PPTX
Rate-Limiting 30 Million requests by Vijay Lakshminarayanan and Girish Koundi...
Redis Labs
 
PPTX
Approaches for application request throttling - dotNetCologne
Maarten Balliauw
 
PPTX
Get more than a cache back! - ConFoo Montreal
Maarten Balliauw
 
PPTX
Rate limiters in big data systems
Sandeep Joshi
 
Rate limiting
Viyaan Jhiingade
 
mar07-redis.pdf
AnisSalhi3
 
Approaches to application request throttling
Maarten Balliauw
 
REDIS + FastAPI: Implementing a Rate Limiter
techprane
 
Approaches for application request throttling - Cloud Developer Days Poland
Maarten Balliauw
 
An Introduction to Redis for Developers.pdf
Stephen Lorello
 
Redis Everywhere - Sunshine PHP
Ricard Clau
 
Mini-Training: Redis
Betclic Everest Group Tech Team
 
Rate limits and all about
Alexander Tokarev
 
ConFoo Montreal - Approaches for application request throttling
Maarten Balliauw
 
Introduction to Redis
Ofer Zelig
 
Scaling Redis To 1M Ops/Sec: Jane Paek
Redis Labs
 
Tuga IT 2017 - Redis
Nuno Caneco
 
Redis Labcamp
Angelo Simone Scotto
 
Introduction to Redis
Dvir Volk
 
Rate-Limiting 30 Million requests by Vijay Lakshminarayanan and Girish Koundi...
Redis Labs
 
Approaches for application request throttling - dotNetCologne
Maarten Balliauw
 
Get more than a cache back! - ConFoo Montreal
Maarten Balliauw
 
Rate limiters in big data systems
Sandeep Joshi
 
Ad

More from Redis Labs (20)

PPTX
Redis Day Bangalore 2020 - Session state caching with redis
Redis Labs
 
PPTX
Rust and Redis - Solving Problems for Kubernetes by Ravi Jagannathan of VMwar...
Redis Labs
 
PPTX
Redis for Data Science and Engineering by Dmitry Polyakovsky of Oracle
Redis Labs
 
PPTX
Practical Use Cases for ACLs in Redis 6 by Jamie Scott - Redis Day Seattle 2020
Redis Labs
 
PPTX
Moving Beyond Cache by Yiftach Shoolman Redis Labs - Redis Day Seattle 2020
Redis Labs
 
PPTX
Leveraging Redis for System Monitoring by Adam McCormick of SBG - Redis Day S...
Redis Labs
 
PPTX
Highly Available Persistent Session Management Service by Mohamed Elmergawi o...
Redis Labs
 
PPTX
Anatomy of a Redis Command by Madelyn Olson of Amazon Web Services - Redis Da...
Redis Labs
 
PPTX
Building a Multi-dimensional Analytics Engine with RedisGraph by Matthew Goos...
Redis Labs
 
PPTX
RediSearch 1.6 by Pieter Cailliau - Redis Day Bangalore 2020
Redis Labs
 
PPTX
RedisGraph 2.0 by Pieter Cailliau - Redis Day Bangalore 2020
Redis Labs
 
PPTX
RedisAI 0.9 by Sherin Thomas of Tensorwerk - Redis Day Bangalore 2020
Redis Labs
 
PDF
Three Pillars of Observability by Rajalakshmi Raji Srinivasan of Site24x7 Zoh...
Redis Labs
 
PPTX
Solving Complex Scaling Problems by Prashant Kumar and Abhishek Jain of Myntr...
Redis Labs
 
PPTX
Redis as a High Scale Swiss Army Knife by Rahul Dagar and Abhishek Gupta of G...
Redis Labs
 
PPTX
Deploying Redis as a Sidecar in Kubernetes by Janakiram MSV - Redis Day Banga...
Redis Labs
 
PPTX
Moving Beyond Cache by Yiftach Shoolman - Redis Day Bangalore 2020
Redis Labs
 
PPTX
Real-time GeoSearching at Scale with RediSearch by Apoorva Gaurav and Ronil M...
Redis Labs
 
PPTX
Build a High-performance Partner Analytics Platform by Ashish Jadhav and Neer...
Redis Labs
 
PPTX
Build a Deep Learning App with Tensorflow & Redis by Jayesh Ahire and Sherin ...
Redis Labs
 
Redis Day Bangalore 2020 - Session state caching with redis
Redis Labs
 
Rust and Redis - Solving Problems for Kubernetes by Ravi Jagannathan of VMwar...
Redis Labs
 
Redis for Data Science and Engineering by Dmitry Polyakovsky of Oracle
Redis Labs
 
Practical Use Cases for ACLs in Redis 6 by Jamie Scott - Redis Day Seattle 2020
Redis Labs
 
Moving Beyond Cache by Yiftach Shoolman Redis Labs - Redis Day Seattle 2020
Redis Labs
 
Leveraging Redis for System Monitoring by Adam McCormick of SBG - Redis Day S...
Redis Labs
 
Highly Available Persistent Session Management Service by Mohamed Elmergawi o...
Redis Labs
 
Anatomy of a Redis Command by Madelyn Olson of Amazon Web Services - Redis Da...
Redis Labs
 
Building a Multi-dimensional Analytics Engine with RedisGraph by Matthew Goos...
Redis Labs
 
RediSearch 1.6 by Pieter Cailliau - Redis Day Bangalore 2020
Redis Labs
 
RedisGraph 2.0 by Pieter Cailliau - Redis Day Bangalore 2020
Redis Labs
 
RedisAI 0.9 by Sherin Thomas of Tensorwerk - Redis Day Bangalore 2020
Redis Labs
 
Three Pillars of Observability by Rajalakshmi Raji Srinivasan of Site24x7 Zoh...
Redis Labs
 
Solving Complex Scaling Problems by Prashant Kumar and Abhishek Jain of Myntr...
Redis Labs
 
Redis as a High Scale Swiss Army Knife by Rahul Dagar and Abhishek Gupta of G...
Redis Labs
 
Deploying Redis as a Sidecar in Kubernetes by Janakiram MSV - Redis Day Banga...
Redis Labs
 
Moving Beyond Cache by Yiftach Shoolman - Redis Day Bangalore 2020
Redis Labs
 
Real-time GeoSearching at Scale with RediSearch by Apoorva Gaurav and Ronil M...
Redis Labs
 
Build a High-performance Partner Analytics Platform by Ashish Jadhav and Neer...
Redis Labs
 
Build a Deep Learning App with Tensorflow & Redis by Jayesh Ahire and Sherin ...
Redis Labs
 
Ad

Recently uploaded (20)

PDF
Virtual Threads in Java: A New Dimension of Scalability and Performance
Tier1 app
 
PDF
Dialora AI Voice Agent for Customer Support
Dialora. Ai
 
PPTX
SAP Public Cloud PPT , SAP PPT, Public Cloud PPT
sonawanekundan2024
 
PPTX
Transforming Lending with IntelliGrow – Advanced Loan Software Solutions
Intelli grow
 
PDF
Message Level Status (MLS): The Instant Feedback Mechanism for UAE e-Invoicin...
Prachi Desai
 
PDF
How Attendance Management Software is Revolutionizing Education.pdf
Pikmykid
 
PDF
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
PDF
Australian Enterprises Need Project Service Automation
Navision India
 
PPTX
UI5con_2025_Accessibility_Ever_Evolving_
gerganakremenska1
 
PDF
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
PDF
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
PDF
How AI in Healthcare Apps Can Help You Enhance Patient Care?
Lilly Gracia
 
PPTX
iaas vs paas vs saas :choosing your cloud strategy
CloudlayaTechnology
 
PPTX
TexSender Pro 8.9.1 Crack Full Version Download
cracked shares
 
PDF
AI Software Engineering based on Multi-view Modeling and Engineering Patterns
Hironori Washizaki
 
PDF
How to get the licensing right for Microsoft Core Infrastructure Server Suite...
Q-Advise
 
PDF
chapter 5.pdf cyber security and Internet of things
PalakSharma980227
 
PPTX
PCC IT Forum 2025 - Legislative Technology Snapshot
Gareth Oakes
 
PPTX
Chess King 25.0.0.2500 With Crack Full Free Download
cracked shares
 
PDF
Windows 10 Professional Preactivated.pdf
asghxhsagxjah
 
Virtual Threads in Java: A New Dimension of Scalability and Performance
Tier1 app
 
Dialora AI Voice Agent for Customer Support
Dialora. Ai
 
SAP Public Cloud PPT , SAP PPT, Public Cloud PPT
sonawanekundan2024
 
Transforming Lending with IntelliGrow – Advanced Loan Software Solutions
Intelli grow
 
Message Level Status (MLS): The Instant Feedback Mechanism for UAE e-Invoicin...
Prachi Desai
 
How Attendance Management Software is Revolutionizing Education.pdf
Pikmykid
 
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
Australian Enterprises Need Project Service Automation
Navision India
 
UI5con_2025_Accessibility_Ever_Evolving_
gerganakremenska1
 
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
How AI in Healthcare Apps Can Help You Enhance Patient Care?
Lilly Gracia
 
iaas vs paas vs saas :choosing your cloud strategy
CloudlayaTechnology
 
TexSender Pro 8.9.1 Crack Full Version Download
cracked shares
 
AI Software Engineering based on Multi-view Modeling and Engineering Patterns
Hironori Washizaki
 
How to get the licensing right for Microsoft Core Infrastructure Server Suite...
Q-Advise
 
chapter 5.pdf cyber security and Internet of things
PalakSharma980227
 
PCC IT Forum 2025 - Legislative Technology Snapshot
Gareth Oakes
 
Chess King 25.0.0.2500 With Crack Full Free Download
cracked shares
 
Windows 10 Professional Preactivated.pdf
asghxhsagxjah
 

Protecting Your API with Redis by Jane Paek - Redis Day Seattle 2020

  • 1. PRESENTED BY Protecting Your API with Redis Jane Paek – [email protected] Solution Architect Manager, Redis Labs
  • 2. PRESENTED BY Metering and Rate limiting Uses and Design Elements Protect and Scale Your Application with Rate Limiting and Metering 1 2 3 Why Redis for Rate Limiting and Metering Rate Limiting Patterns/ Anti Patterns / Design Considerations Rate Limiting Demo4 5 Resources Rate Limiting Webinar January 16th 2020, 9am PST Redis University FREE classes starting January 21, 2020
  • 3. PRESENTED BY Metering … It’s Everywhere... Pay As You Go Freemium Tiered Pricing Rate LimitingSecurityTraffic Shaping
  • 4. PRESENTED BY Rate Limiting Casualties Load Balancer Bad Actors? Unanticipated Use Cases? Programmatic Errors?
  • 5. PRESENTED BY What Do You Need to Meter and Rate Limit? Load Balancer 1. who - Method for determining client ■ API key ■ JWT Token ■ IP address 2. how - Pattern to measure and limit resources 3. where - Fast centralized data store who how where
  • 6. PRESENTED BY Why Redis for Metering and Rate Limiting? In-Database Analytics Fast Data Ingest High-Speed Transactions 1. Scales to handle burst access at millions of ops/sec at sub ms latency 2. Fast centralized store for resource limit and state 3. Optimized commands to control resources ○ Incr/Decr, Count 4. Granular control of resource lifetime 5. “In database” analytics for leaderboards, ranking, scoring 6. Flexible data structures to meet various metering designs Centralized Store
  • 7. PRESENTED BY Redis Data Structures for Metering and Rate Limiting Lists [ A → B → C → D → E ] Hashes { A: “foo”, B: “bar”, C: “baz” } Bitmaps 0011010101100111001010 Strings "I'm a Plain Text String!” Bit field {23334}{112345569}{766538} Key Streams 🡪{id1=time1.seq1(A:“xyz”, B:“cdf”), d2=time2.seq2(D:“abc”, )}🡪 Hyperloglog 00110101 11001110 Sorted Sets { A: 0.1, B: 0.3, C: 100 } Sets { A , B , C , D , E } Geospatial Indexes { A: (51.5, 0.12), B: (32.1, 34.7) }
  • 8. PRESENTED BY Counting (How Many) Redis Commands Used for Metering and Rate Limiting 8 Lists | LLEN key Set | SCARD key Sorted Set | ZCARD key Hash | HLEN key Hyperloglog | PFCOUNT key Bitmap | BITCOUNT key [start end] EXPIRE key seconds EXPIREAT key timestamp PEXPIRE key milliseconds PEXPIREAT key timestamp SET key value [EX seconds] [PX milliseconds] INCR key INCRBY key increment HINCRBY key field increment ZINCRBY key increment member DECR key DECRBY key decrement TTL key PTTL key Set Key Expiry Check Time to Live Incr/Decr Keys
  • 9. PRESENTED BY • A rate limiter is a tool that monitors user requests in a defined time window • “Users” can be humans or services • Many different designs, each with tradeoffs in: – complexity – data usage – granularity • No one size fits all! • Consider over-limit behavior Today we are examining Rate Limiters as used in distributed systems where a central database (Redis!) is needed. Rate Limiting Design Considerations 9
  • 10. PRESENTED BY Simple Fixed Window Counter Using String • Defined number of requests per time interval • single STRING per client: user:<identifier>:<window start time> • E.g. user:ip-address:start-timestamp user:127.0.0.1:1573767000 • Redis commands used: SET(EX), INCR, TTL • Redis in the background, will expire old keys
  • 11. PRESENTED BY Fixed Window Example: 5 req/min
  • 12. PRESENTED BY Fixed Window Example: 5 req/min
  • 13. PRESENTED BY Fixed Window Example: 5 req/min
  • 14. PRESENTED BY Fixed Window Example: 5 req/min * Issue: Between 1:30 to 2:15 we allowed 7 requests within a 1 min window
  • 15. PRESENTED BY Sliding Window e.g Max 10 req/minute 15 Previous Minute Sliding 60 sec window Current Minute Rejected requests
  • 16. PRESENTED BY Sliding Window e.g Max 10 req/minute 16 Previous Minute Sliding 60 sec window Current Minute Trimmed requests
  • 17. PRESENTED BY Sliding Window e.g Max 10 req/minute 17 Previous Minute Sliding 60 sec window Current Minute Trimmed requests
  • 18. PRESENTED BY Sliding Window Using Sorted Set 18 • Stores timestamps of all requests in one Sorted Set per user • Upon new request: – Add new request timestamp to user’s ZSET – e.g. ZADD user_1 15000000 15000000 – ZREMRANGEBYSCORE to remove expired timestamps for window – ZCARD therefore gives number of requests in current window - if larger than limit deny request • Sliding Window is extremely accurate, but can be memory expensive • Consider trimming sorted set when adding and reading the sorted if split role • Make sure to expire and extend the expiry of the key when values are added Example Redis Sorted Set: Key Value(timestamp) Score(timestamp) user_1 : {1500000000 -> 1500000000, 1510000000 -> 1510000000, .... 1576525629 -> 1576525629}
  • 19. PRESENTED BY Token Bucket Using Hash • For each unique user, store in a hash: – Last request’s timestamp – Count of available “tokens” • Upon new request: – Fetch hash (HGETALL) – Refill tokens based on refill rate using last timestamp as reference (HSET) – Update hash with current timestamp and decrement token count (HMSET) – If no tokens left, deny request • Challenges: – Redis operations not atomic (can lead to race conditions in distributed environment) – Consider using Lua or perform optimistic locking using Watch with Multi-Exec for Check and Set (CAS) operations 19 Example Redis Hash: Key TimeStamp AvailTokens user_1 ->{ts:1576523628, tokens:10}
  • 20. PRESENTED BY Rate Limiting Design Anti-Patterns • Race conditions – Naive designs may not scale in distributed systems – e.g. Token Bucket - look for “get, then set” behaviors • Rate limiting on a super fast API – Use 10% of total request time for limiting as a rule of thumb • Unclear user identification • Granularity vs Resource consumption vs Complexity • Keeping things local vs distributed • Using a slow database – Traditional disk-based databases unable to cope with throughput demands at scale 20
  • 22. PRESENTED BY Rate Limiting Resources Rate Limiting Webinar – January 16th 2020, 9am PST. https://bit.ly/2Nl8b9A Redis University – https://university.redislabs.com/ FREE classes starting January 21, 2020 Articles: https://www.infoworld.com/article/3230455/how-to-use-redis-for-real-time-metering- applications.html Code Samples: https://github.com/redislabsdemo/RateLimiter - Java https://github.com/Redislabs-Solution-Architects/RateLimitingExample - Python 22