Approaches to application request throttling

Maarten Balliauw
Maarten BalliauwDeveloper Advocate
1
Approaches for application
request throttling
Maarten Balliauw
@maartenballiauw
3
Who am I?
Maarten Balliauw
Antwerp, Belgium
Developer Advocate, JetBrains
Founder, MyGet
AZUG
Focus on web
ASP.NET MVC, Azure, SignalR, ...
Former MVP Azure & ASPInsider
Big passion: Azure
http://blog.maartenballiauw.be
@maartenballiauw
4
Agenda
Users and traffic patterns
Rate limiting and considerations
Which resources?
Which limits?
Who to limit? Who not to limit?
What when a limit is reached?
Where to limit?
5
Users...
6
MyGet
Hosted private package repository – www.myget.org
NuGet, NPM, Bower, Maven, VSIX, PHP Composer, Symbols, ...
HTTP-based
Web UI for managing things
API for various package managers
PUT/POST – Upload package
DELETE – Delete package via API
GET – Fetch metadata or binary
7
We’re using background workers
Example: package upload
PUT/POST binary and metadata to front-end
PackageAddedEvent on queue with many handlers handled on back-end
ProcessSymbols
UpdateLatestVersion
Indexing
...
8
What could possibly go wrong...
Too many uploads incoming!
Front-end
IIS server needs workers to read the incoming network stream
Application logic has to check credentials, subscription, quota
Back-end
Delays in queue processing (luckily workers can process at their own pace)
Too many uploads that are too slow!
Front-end
IIS server needs lots of workers to slowly copy from the network stream
Workers == threads == memory == synchronization == not a happy place
9
What could possibly go wrong...
Too many downloads!
Application logic has to check credentials, subscription, quota
404’s still need that application logic...
Package managers are crazy!
Total # requests Total # 404’s % 404’s
# of packages in solution 200 800 600
# on NuGet.org 190 200 10 5%
# on MyGet feed 1 5 200 195 97,5%
# on MyGet feed 2 4 200 196 98%
# on company-internal
TeamCity
1 200 199 99,5%
12
Other examples
Web UI requests
Trying to register spam accounts
Trying to brute-force login/password reset
Trying to validate credit card numbers via a form on your site
Robots / Crawlers
Imagine a spider adding 20k items to a shopping cart
For us, usually fine (e.g. Googlebot by default up to 5 req/sec)
Limiting is easy with rel=“nofollow” and robots.txt crawl-delay
13
Recent, real-life example
14
Rate limiting!
(or “throttling”)
15
Rate limiting – what?
Limits # of requests in a given timeframe
Or limits bandwidth, or another resource – up to you
Helps eliminate:
Unexpected traffic patterns
Unwanted traffic patterns (e.g. script kiddie brute-force login)
Potentiallly damaging traffic patterns
(accidental and malicious)
16
Rate limit everything.
- Maarten Balliauw
17
Rate limiting – everything???
Everything that could slow down or break your application
Typically everything that depends on a scarce or external resource
CPU
Memory
Disk I/O
Database
External API
So yes, everything...
18
Let’s do this!
Database with table Events
UserIdentifier – who do we limit
ActionIdentifier – what do we limit
When – event timestamp so we can apply a query
Filter attribute
SELECT COUNT(*) FROM Events WHERE UserIdentifier = <user> AND
ActionIdentifier = <action> AND When >= NOW() – X
INSERT INTO Events (<user>, <action>, NOW())
DELETE FROM Events WHERE UserIdentifier = <user> AND
ActionIdentifier = <action> AND When < NOW() – X
19
Let’s do this!
demo
20
Rate measuring
21
That database was a bad idea!
Very flexible in defining various limits or doing combinations
Very flexible in changing limits, e.g. changing the time period
The database will suffer at scale...
Every request is at least 2 – 3 queries
Constant index churn
We need to manually run DELETE to remove old events
Database size!
22
That database was a bad idea!
We created a denial of service opportunity!
SELECT, INSERT, DELETE for every request
Consider a simpler technique to limit # of operations
Ideally just a simple counter
“Buckets”
24
Quantized buckets
Create “buckets” per <identifier> and <timespan>
Use incr <bucket> on Redis and get back the current count per <timespan>
public string GetBucketName(string operation, TimeSpan timespan)
{
var bucket = Math.Floor(
DateTime.UtcNow.Ticks / timespan.TotalMilliseconds / 10000);
return $"{operation}_{bucket}";
}
Console.WriteLine(GetBucketName("someaction", TimeSpan.FromMinutes(10)));
// someaction_106062120 <-- this will be the key for +/- 10 minutes
25
Quantized buckets
Super easy and super cheap (atomic write and read on Redis, auto-expire LRU)
Not accurate... (but that may be ok)
(n-1)x2 / 10 sec
Theoretically: max. 6 / 10 sec
26
Leaky bucket
“Imagine a bucket where water is
poured in at the top and leaks from the
bottom.
If the rate at which water is poured in
exceeds the rate at which it leaks, the
bucket overflows.“
Widely used in telecommunications to deal with
bandwidth/bursts.
27
Bucket algorithms
demo
28
Bucket approaches
QUANTIZED BUCKET
Create “buckets” per
<identifier>_<timespan>
No rolling window (new bucket
every <timespan>)
Simple key/value store is
sufficient, 1 atomic read+write
Old keys can auto-expire (unlike
our DB approach)
LEAKY BUCKET
Get <delta> tokens, with maximum
<count> per <timespan>
Rolling window, smooths traffic, allows
bursts when bucket has capacity
Need to store # tokens, last refill,
concurrency needs to be taken into account
Or use a FIFO queue of timestamps (works
great with Redis sorted set)
29
Redis sorted set
as a bucket
Demo
30
Cool! That’s it, right?
31
Deciding on limits
32
Things to decide on
Decide on the resources to limit
Decide on a sensible limit
Come up with an identifier to limit on
Decide on exceptions to the rule
33
Which resources to limit?
...
34
Rate limit everything.
- Maarten Balliauw
35
What are sensible limits?
Approach 1
1. Figure out current # of requests for a certain resource
2. Set limits
3. Get angry phone calls from customers
Approach 2
1. Figure out current # of requests for a certain resource
2. Set limits, but only log when a request would be limited
3. Analyze logs, set new limits, ...
4. Start rate limiting
5. Keep measuring
36
Will you allow bursts or not?
Laddering! Different buckets per identifier and resource...
10 requests per second can be 36000 requests per hour.
But 10 requests per second could also be 1000 requests per hour.
Bucket Operation A Operation B Operation C
Per second 10 10 100
Per minute 60 60 500
Per hour 3600 600 500
...
Steady flow of max.
10/sec
Steady flow of max.
10/sec, but only
600/hour max.
Bursts of up to 100/sec,
but only 500/hour max.
37
What will be the identifier?
Per IP address?
But what with NAT/proxy?
Per user?
But how do you limit anonymous users?
Per session?
But what when the user starts a new session for every request?
Or what if there is no such thing as a session?
Per browser?
But everyone uses Chrome!
38
What will be the identifier?
Probably a combination!
IP address (debatable)
+ User token (or “anonymous”)
+ Session token
+ Headers (user agent + accept-language + some cookie + ...)
39
Decide on exceptions
Do we rate limit all users? Do we have separate limits for certain users?
Dynamic limiting
Do we rate limit all IP addresses?
What about ourselves?
What about our monitoring tools?
What about web crawlers?
What about certain datacenter ranges? (https://github.com/client9/ipcat)
“IP addresses that end web consumers should not be using"
40
Responding to limits
41
What when the user hits the limit?
Do we just “black hole” and close the connection?
Do you tell the user?
API: status code 429 Too Many Requests
Web: error page stating rate limit exceeded / captcha (StackOverflow)
42
Try to always tell the user
Format? Depends on Accept header (text/html vs. application/json)
Tell them why they were throttled
Can be a simple link to API documentation
Tell them when to retry (e.g. GitHub does this even before rate limiting)
Status: 200 OK
X-RateLimit-Limit: 5000
X-RateLimit-Remaining: 4999
X-RateLimit-Reset: 1372700873
43
Where do we limit?
44
Rate limiting – where?
MvcThrottle
Runs as action filter
Requests per timespan
Per action, user, IP, ... (so knows about actions)
Owin.Limits
Runs as OWIN middleware
Bandwidth, concurrent requests, ...
No knowledge about application specifics
Many, many others
45
MvcThrottle
Demo
46
How far do we allow traffic
before saying no?
KNOWLEDGE ABOUT THE OPERATION
RESOURCES SPENT
47
How far do we allow traffic
before saying no?
KNOWLEDGE ABOUT THE OPERATION
RESOURCES SPENT
48
What options are there?
In our application
ActionFilter / Middleware / HttpModule / ...
Easy to add custom logic, based on request details
On the server
Outside of our server
Outside of our datacenter
49
What options are there?
In our application
On the server
IIS has dynamic IP restrictions, bit rate throttling, <limits />
Kestrel minimum speed throttle
Found these less flexible in terms of configuraton...
E.g. IIS dynamic IP restrictions returns 403 Forbidden, wth!
Not a big fan, as these are usually HttpModules anyway (and thus hit our app)
Outside of our server
Outside of our datacenter
50
What options are there?
In our application
On the server
Outside of our server
Reverse proxy (IIS Application Request Routing, NGinx, HAProxy, Squid, ...)
Traffic does not even hit our application server, yay!
Outside of our datacenter
51
Rate limiting with NGinx
Demo
52
What options are there?
In our application
On the server
Outside of our server
Outside of our datacenter
Azure API management, CloudFlare
Filters traffic very early in the request, yay!
Often also handle DDoS attacks
Often more expensive
54
Conclusion
55
Conclusion
Users are crazy! (typically unintended)
We need rate limiting
Decide on the resources to limit (tip: everything)
Decide on a sensible limit (tip: measure)
Come up with an identifier to limit on
Decide on exceptions
What when the user reaches a limit?
Decide where in the request/response flow to limit
56
Thank you!
http://blog.maartenballiauw.be
@maartenballiauw
1 of 51

Recommended

VISUG - Approaches for application request throttling by
VISUG - Approaches for application request throttlingVISUG - Approaches for application request throttling
VISUG - Approaches for application request throttlingMaarten Balliauw
817 views58 slides
Caching Up and Down the Stack by
Caching Up and Down the StackCaching Up and Down the Stack
Caching Up and Down the StackDan Kuebrich
1.2K views59 slides
DDoS: Practical Survival Guide by
DDoS: Practical Survival GuideDDoS: Practical Survival Guide
DDoS: Practical Survival GuideHLL
954 views33 slides
Fredericksburg LUG Bitcoin slides by
Fredericksburg LUG Bitcoin slidesFredericksburg LUG Bitcoin slides
Fredericksburg LUG Bitcoin slidesAlex Akselrod
2.1K views22 slides
Mining pools and attacks by
Mining pools and attacksMining pools and attacks
Mining pools and attacksvpnmentor
9.4K views73 slides
Concept of BlockChain & Decentralized Application by
Concept of BlockChain & Decentralized ApplicationConcept of BlockChain & Decentralized Application
Concept of BlockChain & Decentralized ApplicationSeiji Takahashi
5.1K views63 slides

More Related Content

What's hot

GC Tuning & Troubleshooting Crash Course by
GC Tuning & Troubleshooting Crash CourseGC Tuning & Troubleshooting Crash Course
GC Tuning & Troubleshooting Crash CourseTier1 app
1.7K views50 slides
Gc crash course (1) by
Gc crash course (1)Gc crash course (1)
Gc crash course (1)Tier1 app
359 views50 slides
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES! by
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!async_io
1.5K views27 slides
TLS - 2016 Velocity Training by
TLS - 2016 Velocity TrainingTLS - 2016 Velocity Training
TLS - 2016 Velocity TrainingPatrick Meenan
970 views37 slides
DIY Java Profiler by
DIY Java ProfilerDIY Java Profiler
DIY Java Profileraragozin
1.2K views19 slides
What every Java developer should know about network? by
What every Java developer should know about network?What every Java developer should know about network?
What every Java developer should know about network?aragozin
3.2K views39 slides

What's hot(20)

GC Tuning & Troubleshooting Crash Course by Tier1 app
GC Tuning & Troubleshooting Crash CourseGC Tuning & Troubleshooting Crash Course
GC Tuning & Troubleshooting Crash Course
Tier1 app1.7K views
Gc crash course (1) by Tier1 app
Gc crash course (1)Gc crash course (1)
Gc crash course (1)
Tier1 app359 views
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES! by async_io
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
async_io1.5K views
TLS - 2016 Velocity Training by Patrick Meenan
TLS - 2016 Velocity TrainingTLS - 2016 Velocity Training
TLS - 2016 Velocity Training
Patrick Meenan970 views
DIY Java Profiler by aragozin
DIY Java ProfilerDIY Java Profiler
DIY Java Profiler
aragozin1.2K views
What every Java developer should know about network? by aragozin
What every Java developer should know about network?What every Java developer should know about network?
What every Java developer should know about network?
aragozin3.2K views
Java profiling Do It Yourself by aragozin
Java profiling Do It YourselfJava profiling Do It Yourself
Java profiling Do It Yourself
aragozin1.4K views
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016 by Zabbix
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Zabbix1.5K views
Java on Linux for devs and ops by aragozin
Java on Linux for devs and opsJava on Linux for devs and ops
Java on Linux for devs and ops
aragozin1.1K views
[263] s2graph large-scale-graph-database-with-hbase-2 by NAVER D2
[263] s2graph large-scale-graph-database-with-hbase-2[263] s2graph large-scale-graph-database-with-hbase-2
[263] s2graph large-scale-graph-database-with-hbase-2
NAVER D29.7K views
Defeating The Network Security Infrastructure V1.0 by Philippe Bogaerts
Defeating The Network Security Infrastructure  V1.0Defeating The Network Security Infrastructure  V1.0
Defeating The Network Security Infrastructure V1.0
Philippe Bogaerts420.1K views
HTTP For the Good or the Bad by Xavier Mertens
HTTP For the Good or the BadHTTP For the Good or the Bad
HTTP For the Good or the Bad
Xavier Mertens4.3K views
Low latency in java 8 v5 by Peter Lawrey
Low latency in java 8 v5Low latency in java 8 v5
Low latency in java 8 v5
Peter Lawrey3.9K views
Proper passwordhashing by fangjiafu
Proper passwordhashingProper passwordhashing
Proper passwordhashing
fangjiafu688 views
Latency vs everything by Ori Pekelman
Latency vs everythingLatency vs everything
Latency vs everything
Ori Pekelman334 views

Viewers also liked

Hands-on getdns Tutorial by
Hands-on getdns TutorialHands-on getdns Tutorial
Hands-on getdns TutorialShumon Huque
660 views80 slides
Remediating Violated Customers by
Remediating Violated CustomersRemediating Violated Customers
Remediating Violated CustomersBarry Greene
869 views22 slides
DNS for Developers - NDC Oslo 2016 by
DNS for Developers - NDC Oslo 2016DNS for Developers - NDC Oslo 2016
DNS for Developers - NDC Oslo 2016Maarten Balliauw
1.4K views58 slides
Are you ready for the next attack? reviewing the sp security checklist (apnic... by
Are you ready for the next attack? reviewing the sp security checklist (apnic...Are you ready for the next attack? reviewing the sp security checklist (apnic...
Are you ready for the next attack? reviewing the sp security checklist (apnic...Barry Greene
748 views25 slides
Indusrty Strategy For Action by
Indusrty Strategy For ActionIndusrty Strategy For Action
Indusrty Strategy For ActionBarry Greene
600 views15 slides
Managing Postgres with Ansible by
Managing Postgres with AnsibleManaging Postgres with Ansible
Managing Postgres with AnsibleGulcin Yildirim Jelinek
4.3K views75 slides

Viewers also liked(20)

Hands-on getdns Tutorial by Shumon Huque
Hands-on getdns TutorialHands-on getdns Tutorial
Hands-on getdns Tutorial
Shumon Huque660 views
Remediating Violated Customers by Barry Greene
Remediating Violated CustomersRemediating Violated Customers
Remediating Violated Customers
Barry Greene869 views
DNS for Developers - NDC Oslo 2016 by Maarten Balliauw
DNS for Developers - NDC Oslo 2016DNS for Developers - NDC Oslo 2016
DNS for Developers - NDC Oslo 2016
Maarten Balliauw1.4K views
Are you ready for the next attack? reviewing the sp security checklist (apnic... by Barry Greene
Are you ready for the next attack? reviewing the sp security checklist (apnic...Are you ready for the next attack? reviewing the sp security checklist (apnic...
Are you ready for the next attack? reviewing the sp security checklist (apnic...
Barry Greene748 views
Indusrty Strategy For Action by Barry Greene
Indusrty Strategy For ActionIndusrty Strategy For Action
Indusrty Strategy For Action
Barry Greene600 views
OpenDNS Enterprise Web Content Filtering by OpenDNS
OpenDNS Enterprise Web Content FilteringOpenDNS Enterprise Web Content Filtering
OpenDNS Enterprise Web Content Filtering
OpenDNS1.4K views
Creating Domain Specific Languages in Python by Siddhi
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
Siddhi35.3K views
BIND’s New Security Feature: DNSRPZ - the &quot;DNS Firewall&quot; by Barry Greene
BIND’s New Security Feature: DNSRPZ - the &quot;DNS Firewall&quot;BIND’s New Security Feature: DNSRPZ - the &quot;DNS Firewall&quot;
BIND’s New Security Feature: DNSRPZ - the &quot;DNS Firewall&quot;
Barry Greene12K views
A Designated ENUM DNS Zone Provisioning Architecture by enumplatform
A Designated ENUM DNS Zone Provisioning ArchitectureA Designated ENUM DNS Zone Provisioning Architecture
A Designated ENUM DNS Zone Provisioning Architecture
enumplatform1.1K views
IoT Security in Action - Boston Sept 2015 by Eurotech
IoT Security in Action - Boston Sept 2015IoT Security in Action - Boston Sept 2015
IoT Security in Action - Boston Sept 2015
Eurotech3.4K views
DNS and Troubleshooting DNS issues in Linux by Konkona Basu
DNS and Troubleshooting DNS issues in LinuxDNS and Troubleshooting DNS issues in Linux
DNS and Troubleshooting DNS issues in Linux
Konkona Basu3.4K views
I Have the Power(View) by Will Schroeder
I Have the Power(View)I Have the Power(View)
I Have the Power(View)
Will Schroeder20.8K views
Query-name Minimization and Authoritative Server Behavior by Shumon Huque
Query-name Minimization and Authoritative Server BehaviorQuery-name Minimization and Authoritative Server Behavior
Query-name Minimization and Authoritative Server Behavior
Shumon Huque803 views

Similar to Approaches to application request throttling

ConFoo Montreal - Approaches for application request throttling by
ConFoo Montreal - Approaches for application request throttlingConFoo Montreal - Approaches for application request throttling
ConFoo Montreal - Approaches for application request throttlingMaarten Balliauw
1.2K views49 slides
Approaches for application request throttling - dotNetCologne by
Approaches for application request throttling - dotNetCologneApproaches for application request throttling - dotNetCologne
Approaches for application request throttling - dotNetCologneMaarten Balliauw
246 views52 slides
Approaches for application request throttling - Cloud Developer Days Poland by
Approaches for application request throttling - Cloud Developer Days PolandApproaches for application request throttling - Cloud Developer Days Poland
Approaches for application request throttling - Cloud Developer Days PolandMaarten Balliauw
1.1K views55 slides
Low latency in java 8 by Peter Lawrey by
Low latency in java 8 by Peter Lawrey Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey J On The Beach
9.3K views54 slides
Fronteers 20131205 the realtime web by
Fronteers 20131205   the realtime webFronteers 20131205   the realtime web
Fronteers 20131205 the realtime webBert Wijnants
1K views38 slides
DIY Internet: Snappy, Secure Networking with MinimaLT (JSConf EU 2013) by
DIY Internet: Snappy, Secure Networking with MinimaLT (JSConf EU 2013)DIY Internet: Snappy, Secure Networking with MinimaLT (JSConf EU 2013)
DIY Internet: Snappy, Secure Networking with MinimaLT (JSConf EU 2013)Igalia
2.1K views45 slides

Similar to Approaches to application request throttling(20)

ConFoo Montreal - Approaches for application request throttling by Maarten Balliauw
ConFoo Montreal - Approaches for application request throttlingConFoo Montreal - Approaches for application request throttling
ConFoo Montreal - Approaches for application request throttling
Maarten Balliauw1.2K views
Approaches for application request throttling - dotNetCologne by Maarten Balliauw
Approaches for application request throttling - dotNetCologneApproaches for application request throttling - dotNetCologne
Approaches for application request throttling - dotNetCologne
Maarten Balliauw246 views
Approaches for application request throttling - Cloud Developer Days Poland by Maarten Balliauw
Approaches for application request throttling - Cloud Developer Days PolandApproaches for application request throttling - Cloud Developer Days Poland
Approaches for application request throttling - Cloud Developer Days Poland
Maarten Balliauw1.1K views
Low latency in java 8 by Peter Lawrey by J On The Beach
Low latency in java 8 by Peter Lawrey Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey
J On The Beach9.3K views
Fronteers 20131205 the realtime web by Bert Wijnants
Fronteers 20131205   the realtime webFronteers 20131205   the realtime web
Fronteers 20131205 the realtime web
Bert Wijnants1K views
DIY Internet: Snappy, Secure Networking with MinimaLT (JSConf EU 2013) by Igalia
DIY Internet: Snappy, Secure Networking with MinimaLT (JSConf EU 2013)DIY Internet: Snappy, Secure Networking with MinimaLT (JSConf EU 2013)
DIY Internet: Snappy, Secure Networking with MinimaLT (JSConf EU 2013)
Igalia2.1K views
LISA18: Hidden Linux Metrics with Prometheus eBPF Exporter by Ivan Babrou
LISA18: Hidden Linux Metrics with Prometheus eBPF ExporterLISA18: Hidden Linux Metrics with Prometheus eBPF Exporter
LISA18: Hidden Linux Metrics with Prometheus eBPF Exporter
Ivan Babrou910 views
Monitoring your Python with Prometheus (Python Ireland April 2015) by Brian Brazil
Monitoring your Python with Prometheus (Python Ireland April 2015)Monitoring your Python with Prometheus (Python Ireland April 2015)
Monitoring your Python with Prometheus (Python Ireland April 2015)
Brian Brazil17.3K views
FreeSWITCH as a Microservice by Evan McGee
FreeSWITCH as a MicroserviceFreeSWITCH as a Microservice
FreeSWITCH as a Microservice
Evan McGee3.4K views
Scalable Apache for Beginners by webhostingguy
Scalable Apache for BeginnersScalable Apache for Beginners
Scalable Apache for Beginners
webhostingguy2.9K views
Non-blocking I/O, Event loops and node.js by Marcus Frödin
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
Marcus Frödin22.8K views
Scaling Push Messaging for Millions of Devices @Netflix by C4Media
Scaling Push Messaging for Millions of Devices @NetflixScaling Push Messaging for Millions of Devices @Netflix
Scaling Push Messaging for Millions of Devices @Netflix
C4Media1.5K views
Scaling asp.net websites to millions of users by oazabir
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
oazabir65.2K views
Tweaking performance on high-load projects by Dmitriy Dumanskiy
Tweaking performance on high-load projectsTweaking performance on high-load projects
Tweaking performance on high-load projects
Dmitriy Dumanskiy2.5K views
Application Monitoring using Open Source: VictoriaMetrics - ClickHouse by VictoriaMetrics
Application Monitoring using Open Source: VictoriaMetrics - ClickHouseApplication Monitoring using Open Source: VictoriaMetrics - ClickHouse
Application Monitoring using Open Source: VictoriaMetrics - ClickHouse
VictoriaMetrics180 views
Application Monitoring using Open Source - VictoriaMetrics & Altinity ClickHo... by Altinity Ltd
Application Monitoring using Open Source - VictoriaMetrics & Altinity ClickHo...Application Monitoring using Open Source - VictoriaMetrics & Altinity ClickHo...
Application Monitoring using Open Source - VictoriaMetrics & Altinity ClickHo...
Altinity Ltd396 views
"Swoole: double troubles in c", Alexandr Vronskiy by Fwdays
"Swoole: double troubles in c", Alexandr Vronskiy"Swoole: double troubles in c", Alexandr Vronskiy
"Swoole: double troubles in c", Alexandr Vronskiy
Fwdays874 views
The Real World - Plugging the Enterprise Into It (nodejs) by Aman Kohli
The Real World - Plugging  the Enterprise Into It (nodejs)The Real World - Plugging  the Enterprise Into It (nodejs)
The Real World - Plugging the Enterprise Into It (nodejs)
Aman Kohli1.1K views

More from Maarten Balliauw

Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s... by
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...Maarten Balliauw
360 views64 slides
Building a friendly .NET SDK to connect to Space by
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceMaarten Balliauw
182 views47 slides
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo... by
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...Maarten Balliauw
406 views52 slides
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday... by
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...Maarten Balliauw
180 views32 slides
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain... by
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...Maarten Balliauw
326 views53 slides
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m... by
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...Maarten Balliauw
280 views42 slides

More from Maarten Balliauw(20)

Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s... by Maarten Balliauw
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
Maarten Balliauw360 views
Building a friendly .NET SDK to connect to Space by Maarten Balliauw
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
Maarten Balliauw182 views
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo... by Maarten Balliauw
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Maarten Balliauw406 views
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday... by Maarten Balliauw
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Maarten Balliauw180 views
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain... by Maarten Balliauw
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
Maarten Balliauw326 views
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m... by Maarten Balliauw
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
Maarten Balliauw280 views
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se... by Maarten Balliauw
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se....NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
Maarten Balliauw290 views
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S... by Maarten Balliauw
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
Maarten Balliauw564 views
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search by Maarten Balliauw
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and SearchNDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
Maarten Balliauw958 views
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve... by Maarten Balliauw
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Maarten Balliauw1.1K views
CodeStock - Exploring .NET memory management - a trip down memory lane by Maarten Balliauw
CodeStock - Exploring .NET memory management - a trip down memory laneCodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory lane
Maarten Balliauw1.9K views
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain... by Maarten Balliauw
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
Maarten Balliauw1.2K views
Microservices for building an IDE – The innards of JetBrains Rider - TechDays... by Maarten Balliauw
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
Maarten Balliauw10.5K views
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory... by Maarten Balliauw
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
Maarten Balliauw1.1K views
DotNetFest - Let’s refresh our memory! Memory management in .NET by Maarten Balliauw
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
Maarten Balliauw480 views
What is going on - Application diagnostics on Azure - TechDays Finland by Maarten Balliauw
What is going on - Application diagnostics on Azure - TechDays FinlandWhat is going on - Application diagnostics on Azure - TechDays Finland
What is going on - Application diagnostics on Azure - TechDays Finland
Maarten Balliauw746 views
ConFoo - Exploring .NET’s memory management – a trip down memory lane by Maarten Balliauw
ConFoo - Exploring .NET’s memory management – a trip down memory laneConFoo - Exploring .NET’s memory management – a trip down memory lane
ConFoo - Exploring .NET’s memory management – a trip down memory lane
Maarten Balliauw523 views
NuGet beyond Hello World - DotNext Piter 2017 by Maarten Balliauw
NuGet beyond Hello World - DotNext Piter 2017NuGet beyond Hello World - DotNext Piter 2017
NuGet beyond Hello World - DotNext Piter 2017
Maarten Balliauw702 views
Exploring .NET memory management (iSense) by Maarten Balliauw
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)
Maarten Balliauw381 views

Recently uploaded

Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...ShapeBlue
101 views17 slides
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueShapeBlue
93 views15 slides
Qualifying SaaS, IaaS.pptx by
Qualifying SaaS, IaaS.pptxQualifying SaaS, IaaS.pptx
Qualifying SaaS, IaaS.pptxSachin Bhandari
897 views8 slides
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ by
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericShapeBlue
88 views9 slides
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ... by
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...ShapeBlue
85 views10 slides
"Surviving highload with Node.js", Andrii Shumada by
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada Fwdays
53 views29 slides

Recently uploaded(20)

Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by ShapeBlue
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
ShapeBlue101 views
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
ShapeBlue93 views
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ by ShapeBlue
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
ShapeBlue88 views
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ... by ShapeBlue
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
ShapeBlue85 views
"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays53 views
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... by ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue98 views
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading... by The Digital Insurer
Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading...
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And... by ShapeBlue
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
ShapeBlue63 views
Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ... by ShapeBlue
Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ...Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ...
Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ...
ShapeBlue146 views
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson156 views
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by ShapeBlue
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
ShapeBlue138 views
State of the Union - Rohit Yadav - Apache CloudStack by ShapeBlue
State of the Union - Rohit Yadav - Apache CloudStackState of the Union - Rohit Yadav - Apache CloudStack
State of the Union - Rohit Yadav - Apache CloudStack
ShapeBlue253 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue179 views
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue by ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
ShapeBlue176 views
Extending KVM Host HA for Non-NFS Storage - Alex Ivanov - StorPool by ShapeBlue
Extending KVM Host HA for Non-NFS Storage -  Alex Ivanov - StorPoolExtending KVM Host HA for Non-NFS Storage -  Alex Ivanov - StorPool
Extending KVM Host HA for Non-NFS Storage - Alex Ivanov - StorPool
ShapeBlue84 views
Business Analyst Series 2023 - Week 4 Session 7 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7
DianaGray10126 views
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue by ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue163 views

Approaches to application request throttling

  • 1. 1 Approaches for application request throttling Maarten Balliauw @maartenballiauw
  • 2. 3 Who am I? Maarten Balliauw Antwerp, Belgium Developer Advocate, JetBrains Founder, MyGet AZUG Focus on web ASP.NET MVC, Azure, SignalR, ... Former MVP Azure & ASPInsider Big passion: Azure http://blog.maartenballiauw.be @maartenballiauw
  • 3. 4 Agenda Users and traffic patterns Rate limiting and considerations Which resources? Which limits? Who to limit? Who not to limit? What when a limit is reached? Where to limit?
  • 5. 6 MyGet Hosted private package repository – www.myget.org NuGet, NPM, Bower, Maven, VSIX, PHP Composer, Symbols, ... HTTP-based Web UI for managing things API for various package managers PUT/POST – Upload package DELETE – Delete package via API GET – Fetch metadata or binary
  • 6. 7 We’re using background workers Example: package upload PUT/POST binary and metadata to front-end PackageAddedEvent on queue with many handlers handled on back-end ProcessSymbols UpdateLatestVersion Indexing ...
  • 7. 8 What could possibly go wrong... Too many uploads incoming! Front-end IIS server needs workers to read the incoming network stream Application logic has to check credentials, subscription, quota Back-end Delays in queue processing (luckily workers can process at their own pace) Too many uploads that are too slow! Front-end IIS server needs lots of workers to slowly copy from the network stream Workers == threads == memory == synchronization == not a happy place
  • 8. 9 What could possibly go wrong... Too many downloads! Application logic has to check credentials, subscription, quota 404’s still need that application logic... Package managers are crazy! Total # requests Total # 404’s % 404’s # of packages in solution 200 800 600 # on NuGet.org 190 200 10 5% # on MyGet feed 1 5 200 195 97,5% # on MyGet feed 2 4 200 196 98% # on company-internal TeamCity 1 200 199 99,5%
  • 9. 12 Other examples Web UI requests Trying to register spam accounts Trying to brute-force login/password reset Trying to validate credit card numbers via a form on your site Robots / Crawlers Imagine a spider adding 20k items to a shopping cart For us, usually fine (e.g. Googlebot by default up to 5 req/sec) Limiting is easy with rel=“nofollow” and robots.txt crawl-delay
  • 12. 15 Rate limiting – what? Limits # of requests in a given timeframe Or limits bandwidth, or another resource – up to you Helps eliminate: Unexpected traffic patterns Unwanted traffic patterns (e.g. script kiddie brute-force login) Potentiallly damaging traffic patterns (accidental and malicious)
  • 13. 16 Rate limit everything. - Maarten Balliauw
  • 14. 17 Rate limiting – everything??? Everything that could slow down or break your application Typically everything that depends on a scarce or external resource CPU Memory Disk I/O Database External API So yes, everything...
  • 15. 18 Let’s do this! Database with table Events UserIdentifier – who do we limit ActionIdentifier – what do we limit When – event timestamp so we can apply a query Filter attribute SELECT COUNT(*) FROM Events WHERE UserIdentifier = <user> AND ActionIdentifier = <action> AND When >= NOW() – X INSERT INTO Events (<user>, <action>, NOW()) DELETE FROM Events WHERE UserIdentifier = <user> AND ActionIdentifier = <action> AND When < NOW() – X
  • 18. 21 That database was a bad idea! Very flexible in defining various limits or doing combinations Very flexible in changing limits, e.g. changing the time period The database will suffer at scale... Every request is at least 2 – 3 queries Constant index churn We need to manually run DELETE to remove old events Database size!
  • 19. 22 That database was a bad idea! We created a denial of service opportunity! SELECT, INSERT, DELETE for every request Consider a simpler technique to limit # of operations Ideally just a simple counter “Buckets”
  • 20. 24 Quantized buckets Create “buckets” per <identifier> and <timespan> Use incr <bucket> on Redis and get back the current count per <timespan> public string GetBucketName(string operation, TimeSpan timespan) { var bucket = Math.Floor( DateTime.UtcNow.Ticks / timespan.TotalMilliseconds / 10000); return $"{operation}_{bucket}"; } Console.WriteLine(GetBucketName("someaction", TimeSpan.FromMinutes(10))); // someaction_106062120 <-- this will be the key for +/- 10 minutes
  • 21. 25 Quantized buckets Super easy and super cheap (atomic write and read on Redis, auto-expire LRU) Not accurate... (but that may be ok) (n-1)x2 / 10 sec Theoretically: max. 6 / 10 sec
  • 22. 26 Leaky bucket “Imagine a bucket where water is poured in at the top and leaks from the bottom. If the rate at which water is poured in exceeds the rate at which it leaks, the bucket overflows.“ Widely used in telecommunications to deal with bandwidth/bursts.
  • 24. 28 Bucket approaches QUANTIZED BUCKET Create “buckets” per <identifier>_<timespan> No rolling window (new bucket every <timespan>) Simple key/value store is sufficient, 1 atomic read+write Old keys can auto-expire (unlike our DB approach) LEAKY BUCKET Get <delta> tokens, with maximum <count> per <timespan> Rolling window, smooths traffic, allows bursts when bucket has capacity Need to store # tokens, last refill, concurrency needs to be taken into account Or use a FIFO queue of timestamps (works great with Redis sorted set)
  • 25. 29 Redis sorted set as a bucket Demo
  • 28. 32 Things to decide on Decide on the resources to limit Decide on a sensible limit Come up with an identifier to limit on Decide on exceptions to the rule
  • 29. 33 Which resources to limit? ...
  • 30. 34 Rate limit everything. - Maarten Balliauw
  • 31. 35 What are sensible limits? Approach 1 1. Figure out current # of requests for a certain resource 2. Set limits 3. Get angry phone calls from customers Approach 2 1. Figure out current # of requests for a certain resource 2. Set limits, but only log when a request would be limited 3. Analyze logs, set new limits, ... 4. Start rate limiting 5. Keep measuring
  • 32. 36 Will you allow bursts or not? Laddering! Different buckets per identifier and resource... 10 requests per second can be 36000 requests per hour. But 10 requests per second could also be 1000 requests per hour. Bucket Operation A Operation B Operation C Per second 10 10 100 Per minute 60 60 500 Per hour 3600 600 500 ... Steady flow of max. 10/sec Steady flow of max. 10/sec, but only 600/hour max. Bursts of up to 100/sec, but only 500/hour max.
  • 33. 37 What will be the identifier? Per IP address? But what with NAT/proxy? Per user? But how do you limit anonymous users? Per session? But what when the user starts a new session for every request? Or what if there is no such thing as a session? Per browser? But everyone uses Chrome!
  • 34. 38 What will be the identifier? Probably a combination! IP address (debatable) + User token (or “anonymous”) + Session token + Headers (user agent + accept-language + some cookie + ...)
  • 35. 39 Decide on exceptions Do we rate limit all users? Do we have separate limits for certain users? Dynamic limiting Do we rate limit all IP addresses? What about ourselves? What about our monitoring tools? What about web crawlers? What about certain datacenter ranges? (https://github.com/client9/ipcat) “IP addresses that end web consumers should not be using"
  • 37. 41 What when the user hits the limit? Do we just “black hole” and close the connection? Do you tell the user? API: status code 429 Too Many Requests Web: error page stating rate limit exceeded / captcha (StackOverflow)
  • 38. 42 Try to always tell the user Format? Depends on Accept header (text/html vs. application/json) Tell them why they were throttled Can be a simple link to API documentation Tell them when to retry (e.g. GitHub does this even before rate limiting) Status: 200 OK X-RateLimit-Limit: 5000 X-RateLimit-Remaining: 4999 X-RateLimit-Reset: 1372700873
  • 39. 43 Where do we limit?
  • 40. 44 Rate limiting – where? MvcThrottle Runs as action filter Requests per timespan Per action, user, IP, ... (so knows about actions) Owin.Limits Runs as OWIN middleware Bandwidth, concurrent requests, ... No knowledge about application specifics Many, many others
  • 42. 46 How far do we allow traffic before saying no? KNOWLEDGE ABOUT THE OPERATION RESOURCES SPENT
  • 43. 47 How far do we allow traffic before saying no? KNOWLEDGE ABOUT THE OPERATION RESOURCES SPENT
  • 44. 48 What options are there? In our application ActionFilter / Middleware / HttpModule / ... Easy to add custom logic, based on request details On the server Outside of our server Outside of our datacenter
  • 45. 49 What options are there? In our application On the server IIS has dynamic IP restrictions, bit rate throttling, <limits /> Kestrel minimum speed throttle Found these less flexible in terms of configuraton... E.g. IIS dynamic IP restrictions returns 403 Forbidden, wth! Not a big fan, as these are usually HttpModules anyway (and thus hit our app) Outside of our server Outside of our datacenter
  • 46. 50 What options are there? In our application On the server Outside of our server Reverse proxy (IIS Application Request Routing, NGinx, HAProxy, Squid, ...) Traffic does not even hit our application server, yay! Outside of our datacenter
  • 47. 51 Rate limiting with NGinx Demo
  • 48. 52 What options are there? In our application On the server Outside of our server Outside of our datacenter Azure API management, CloudFlare Filters traffic very early in the request, yay! Often also handle DDoS attacks Often more expensive
  • 50. 55 Conclusion Users are crazy! (typically unintended) We need rate limiting Decide on the resources to limit (tip: everything) Decide on a sensible limit (tip: measure) Come up with an identifier to limit on Decide on exceptions What when the user reaches a limit? Decide where in the request/response flow to limit

Editor's Notes

  1. https://pixabay.com
  2. https://pixabay.com/en/tires-used-tires-pfu-garbage-1846674/
  3. https://pixabay.com/en/tires-used-tires-pfu-garbage-1846674/
  4. Prerequisites: create database and make sure it works! Open demo 01 - DemoLetsDoThis.sln In Startup.cs explain adding EF context and show how EventsContext is built Next, show RateLimitFilter is applied to every request Implementation of RateLimitFilter Uses an identifier for the user (either User.Identity.Username or “anonymous” + IP address) Uses ControllerActionDescriptor to determine controller + action We then check if there are > 5 requests to this resource We always add an event to the DB – DANGEROUS!!! And drop older events Show in Fiddler, requesting: http://localhost:56983/api/hello/maarten
  5. Open DemoTokenBuckets.sln Show our quantized bucket implementation QuantizedBucket We give it a rate and an interval, so 5 requests per 5 seconds We use the bucket name, which is based on Math.Floor(Now.Ticks / TimeSpan.Ticks) When bucket empty, block Bucket auto-refills when Math.Floor(Now.Ticks / TimeSpan.Ticks) returns another value Run the app, show request rate allows 5 new requests every 5 seconds Explain again that at the end of my 5 seconds, I could potentially run 8 requests per 10 seconds Leaky bucket fixes this – show LeakyBucket implementation Also takes rate and interval Whenever we consume, we calculate the number of tokens left by looking at the timespan that elapsed between requests. Downside: need to store both # tokens left and last refill time Run the app, show we get a better distribution like in our pizza oven, where we are effectively flattening our traffic now.
  6. Prerequisites: run Redis! Open Patterns03RateLimiting.sln Show our HelloWorldController, say we use an API key this time In WebApiConfig, note we add ThrottlingHandler Run the application, and in Fiddler request http://localhost:9400/api/helloworld Add X-ApiKey header See we are rate limited per API key, open ThrottlingHandler We are using a sorted set as the data type Sorted set has two things: a key, and a score. We’ll use the current timestamp for both, but important is the score is our tmestamp 1) Drop old items with a score below our reference time 2) Count elements 3) Add element with score == now
  7. Open MvcThrottle, in project MvcThrottle.Demo Show HomeController, show EnableThrottling attribute Run the application - http://localhost:53048/Home/About – see it in action after a few refreshes Mention we can respond to throttlign depending on the client type! Open MvcThrottleCustomFilter See filterContext.HttpContext.Request.AcceptTypes.Any(accept => accept.Contains("html")) -> custom view result Mention we can filter based on client IP In FilterConfig.cs, there is an IP whitelist of folks we never want to throttle Same goes with user agents Same goes with endpoints The REALLY nice thing: I can enable/disable per action in MVC Show BlogController REALLY NICE, throttling follows my logic The SAD thing: open 04-snapshot I did a load test – non scientific! This thing has low overhead (did a few thousand requests) but still my aplication spent 12% of its time rate limiting requests
  8. Run the nginx docker container from 05-nginx Show a few requests: http://localhost:8080/ proxies MyGet http://localhost:8080/F/googleanalyticstracker/api/v2 proxies a feed A few refreshes of http://localhost:8080/F/googleanalyticstracker/api/v2 get throttled So we proxy our app, and get to rate limit some calls, sweet! Open nginx.conf and go through some boiler-plate: Worker processes and worker connections (typically == to # cores) http section sets up a web server, we can add SSL etc here as well Under server, we define the different resources / just proxies www.myget.org and injects a header /Content proxies and caches (yay added bonus of NGinx) /F/ is where things get interesting – we limit requests to this one using “mylimit” Defines a key, names a zone, names the timespan, names the limit Can mix and match to create key: limit_req_zone $binary_remote_addr$http_authorization zone=mylimit:10m rate=2r/s;
  9. Prerequisites Create Azure API management (!!! Well upfront – takes time !!!) Force-push the 06-apim repo to it git remote add origin .......<new url>....... git push --force --set-upstream origin master Show portal – especially “API” and “PRODUCT” “API” defines API calls. From portal, show we can create this based on a Swagger definition For demo here, created manually and registered /F/* and /* to just pass-through Under products Show anonymous and unlimited Explain the idea of API management is to sell access to your API and allow people to purchase a product to get better/less/… access to an API Anonymous is all I’ll use during the demo Anonymous has policies – show rate limit is 100 per 60 sec From PUBLISHER PORTAL (click), we have a policy for –Feed endpoint as well, which is more strict Show https://ratelimitingdemo.azure-api.net/ is smooth Show a few refreshes of https://shit.azure-api.net/F/googleanalyticstracker/api/v2/  limited Requests that are limited never hit my server