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

PPTX
A Low-latency Logging Framework by Rajat Panwar of HolidayMe - Redis Day Bang...
PPTX
RedisTimeSeries 1.2 by Pieter Cailliau - Redis Day Bangalore 2020
PPTX
JSON in Redis - When to use RedisJSON by Jay Won of Coupang - Redis Day Seatt...
PPTX
RedisConf18 - My Other Car is a Redis Cluster
PDF
RedisConf18 - Redis Memory Optimization
PPTX
RedisConf17 - Home Depot - Turbo charging existing applications with Redis
PPTX
The Happy Marriage of Redis and Protobuf by Scott Haines of Twilio - Redis Da...
PDF
RedisConf18 - Active-Active Geo-Distributed Apps with Redis CRDTs (conflict f...
A Low-latency Logging Framework by Rajat Panwar of HolidayMe - Redis Day Bang...
RedisTimeSeries 1.2 by Pieter Cailliau - Redis Day Bangalore 2020
JSON in Redis - When to use RedisJSON by Jay Won of Coupang - Redis Day Seatt...
RedisConf18 - My Other Car is a Redis Cluster
RedisConf18 - Redis Memory Optimization
RedisConf17 - Home Depot - Turbo charging existing applications with Redis
The Happy Marriage of Redis and Protobuf by Scott Haines of Twilio - Redis Da...
RedisConf18 - Active-Active Geo-Distributed Apps with Redis CRDTs (conflict f...

What's hot (20)

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

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

PPTX
IBM IoT Architecture and Capabilities at the Edge and Cloud
PDF
How to create custom dashboards in Elastic Search / Kibana with Performance V...
PDF
IBM Internet-of-Things architecture and capabilities
PPTX
Rate limits and all about
PDF
Monitoring and Scaling Redis at DataDog - Ilan Rabinovitch, DataDog
PPT
Everything You Need to Know About Sharding
PPTX
Lessons learned from embedding Cassandra in xPatterns
PDF
Donatas Mažionis, Building low latency web APIs
PDF
Performance Testing Java Applications
PDF
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
PDF
The Diabolical Developers Guide to Performance Tuning
PDF
Ibm_IoT_Architecture_and_Capabilities
PPTX
NoSQL em Windows Azure Table Storage - Vitor Tomaz
PDF
Three Perspectives on Measuring Latency
PPTX
Big Data Day LA 2016/ NoSQL track - Analytics at the Speed of Light with Redi...
PPTX
MongoDB.local Atlanta: MongoDB @ Sensus: Xylem IoT and MongoDB
PPTX
Managing Performance Globally with MySQL
PDF
Aerospike Hybrid Memory Architecture
PDF
Measuring CDN performance and why you're doing it wrong
PPTX
Dynamics CRM high volume systems - lessons from the field
IBM IoT Architecture and Capabilities at the Edge and Cloud
How to create custom dashboards in Elastic Search / Kibana with Performance V...
IBM Internet-of-Things architecture and capabilities
Rate limits and all about
Monitoring and Scaling Redis at DataDog - Ilan Rabinovitch, DataDog
Everything You Need to Know About Sharding
Lessons learned from embedding Cassandra in xPatterns
Donatas Mažionis, Building low latency web APIs
Performance Testing Java Applications
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
The Diabolical Developers Guide to Performance Tuning
Ibm_IoT_Architecture_and_Capabilities
NoSQL em Windows Azure Table Storage - Vitor Tomaz
Three Perspectives on Measuring Latency
Big Data Day LA 2016/ NoSQL track - Analytics at the Speed of Light with Redi...
MongoDB.local Atlanta: MongoDB @ Sensus: Xylem IoT and MongoDB
Managing Performance Globally with MySQL
Aerospike Hybrid Memory Architecture
Measuring CDN performance and why you're doing it wrong
Dynamics CRM high volume systems - lessons from the field
Ad

More from Redis Labs (20)

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

Recently uploaded (20)

PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Transform Your Business with a Software ERP System
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PPT
Introduction Database Management System for Course Database
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Complete React Javascript Course Syllabus.pdf
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
ai tools demonstartion for schools and inter college
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
AI in Product Development-omnex systems
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
VVF-Customer-Presentation2025-Ver1.9.pptx
Understanding Forklifts - TECH EHS Solution
Transform Your Business with a Software ERP System
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Introduction Database Management System for Course Database
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Complete React Javascript Course Syllabus.pdf
Online Work Permit System for Fast Permit Processing
Odoo POS Development Services by CandidRoot Solutions
ai tools demonstartion for schools and inter college
Wondershare Filmora 15 Crack With Activation Key [2025
AI in Product Development-omnex systems
PTS Company Brochure 2025 (1).pdf.......
How to Migrate SBCGlobal Email to Yahoo Easily
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool

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

  • 1. PRESENTED BY Protecting Your API with Redis Jane Paek – Jane@redislabs.com 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