forked from mcastilho/marcio.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.xml
428 lines (292 loc) · 19.8 KB
/
index.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>rafaelcapucho.com</title>
<generator uri="https://hugo.spf13.com">Hugo</generator>
<link>https://rafaelcapucho.github.io/</link>
<language>en-us</language>
<author>Rafael Capucho</author>
<copyright>2017 Rafael Capucho</copyright>
<updated>Wed, 18 Jan 2017 00:00:00 UTC</updated>
<item>
<title>Enhance the quality of your API calls with Client-Side Throttling</title>
<link>https://rafaelcapucho.github.io/2016/10/enhance-the-quality-of-your-api-calls-with-client-side-throttling/</link>
<pubDate>Sun, 02 Oct 2016 00:00:00 UTC</pubDate>
<author>Rafael Capucho</author>
<guid>https://rafaelcapucho.github.io/2016/10/enhance-the-quality-of-your-api-calls-with-client-side-throttling/</guid>
<description>
<p>If you are a backend engineer and work with high load environment you <strong>should</strong> be familiarized with the old Server-Side Rate Limit, mainly for security concerns.</p>
<p>Didn&rsquo;t you ever heard about Server-Side Rate Limit? It is a technique to limit the amount of requests that the server or API can handle in a defined period of time, and that limit can be set per user or not.</p>
<p>Throttling is often used to limiting traffic on the server, mainly as a way to protect against <a href="https://en.wikipedia.org/wiki/Denial-of-service_attack">DOS Attack</a>. Additionally, it can also be used on the client-side, as this article describes.</p>
<p>When a rate limit is exceeded, all requests are throttled and fail for a brief period of time or until the activities back to normal. Once throttled, the caller usually get the HTTP 403 (forbidden) status as response.</p>
<p><img src="https://rafaelcapucho.github.io/img/client-side-throttling/Rate-Limit-and-Throttling-Graph.jpg" alt="Rate Limit &amp; Throttling Graph" /></p>
<p>In the above picture, the user #3 are exceeding the global or individual rate limiting, being throttled to guarantee the quality of service and security.</p>
<h2 id="just-reject-the-requests-is-enough">Just reject the requests is enough?</h2>
<p>When a user is throttled, his next requests calls will be rejected. This behavior consumes significantly fewer resources than actually processing the requests and serving back correct responses.</p>
<p>If a request were simple, like only retrieving information from local memory, it is almost equally expensive to reject it as it is to accept it and return the expected result.</p>
<p>Additionally, we should consider that the server also allocates resources to receive the requests, establishing a complete TCP connection to finally reject them. Helping DDoS attackers.</p>
<h2 id="big-mistake-when-consuming-apis">Big mistake when consuming APIs.</h2>
<p>Consider that you are creating the new version of Facebook client, that makes periodics requests to Facebook API to collect news feed, comments, likes, online users etc.</p>
<p>Almost everytime happens that unprepared clients, once throttled and getting rejected requests from API, keep making the same amount of requests, trying to reach the data.</p>
<p>As result, the API keep blocking the user to maintain the overall quality of the service and your client could never retrieve the data as desired.</p>
<h2 id="how-to-apply-client-side-throttling-with-adaptive-throttling">How to apply Client-Side Throttling with Adaptive Throttling?</h2>
<p>When a client detects that a significant portion of its recent requests have been rejected, it starts self-regulating and caps the amount of outgoing traffic it generates.</p>
<p>Requests above the cap should fail locally without even reaching the network.</p>
<p><strong><em>Adaptive throttling</em></strong> is the key to solve the problem. To implement this technique the client needs to keep the following information for at least two minutes of its history:</p>
<ul>
<li><strong>Requests</strong>: The number of requests attempted by the application.</li>
<li><strong>Accepts</strong>: The number of requests accepted by the backend.</li>
</ul>
<p>When everything is fine at the client, the two values are equal. Once the API start rejecting the client requests the number of <em>Accepts</em> becomes smaller than the number of <em>Requests</em>.</p>
<p>The client app should still be able to issue requests to the API until the <strong>Requests</strong> be <strong>K</strong> times grather than <strong>Accepts</strong>, assuming K &gt; 1.</p>
<p>For example, <strong>K = 1.1</strong> means that the client will allow one <em>Reject</em> for each 10 <em>Accepts</em>.</p>
<p>Once the threshold is surpassed, which will happen when the state of the system meet the criteria <strong>Requests &gt; k * Accepts</strong>, the app should be able to self-regulate and new requests are now reject locally based on the probability P<sub>0</sub> described below.</p>
<p><img src="https://rafaelcapucho.github.io/img/client-side-throttling/adaptative-throttling.jpg" alt="Adaptive throttling Probability" /></p>
<p>Example, the client app performed <strong>1000 Requests</strong> in the last 2 minutes, with <strong>600 of them Accepted</strong>. Also, our system is designed to allow 4 rejects for each 10 requests which means that our <strong>K = 1.4</strong>.</p>
<p>In the previous scenario the app should start regulating new request based on P<sub>0</sub> since the initial criteria is meet:</p>
<p><img src="https://rafaelcapucho.github.io/img/client-side-throttling/initial-criteria.jpg" alt="Initial Criteria" /></p>
<p>Since the client app is issuing more requests than our sample <strong>K</strong> allow, the app should reject new requests locally to the server with probability equal to 0.16, rejecting 16 requests in 100:</p>
<p><img src="https://rafaelcapucho.github.io/img/client-side-throttling/probability-answer.jpg" alt="Probability Answer" /></p>
<h2 id="the-problem-with-that-approach">The problem with that approach</h2>
<p>The P<sub>0</sub> probability is originally defined in the Chapter 21 of the book <a href="https://www.amazon.com/Site-Reliability-Engineering-Production-Systems/dp/149192912X" target="_blank">Site Reliability Engineering: How Google Runs Production Systems</a> by, guess who? Google guys.</p>
<p>The main goal is to increase the probability of dropping new requests, as soon as the server appears to be overloaded (assuming a small value of <strong>K</strong>). Doing this, every client instance will help the server recover faster from the outage, by using less resources.</p>
<p>Also, this approach is used in some Google services and they suggest K = 2, based on their own experiences.</p>
<p>My concerns about this probability is that, if the server goes down for more than 2 minutes, the P<sub>0</sub> value will stand in 1, rejecting locally every new request to the server, so the client app won&rsquo;t be able to set up a new conection. As the result of it, the client app will never have another request reaching the server.</p>
<p>I would like to suggest a new probability measure, P<sub>1</sub>, that upper limits the chance of rejecting a new request to 90%, allowing the client to recover even in that worst scenario, when the service is down more than 2 minutes.</p>
<p><img src="https://rafaelcapucho.github.io/img/client-side-throttling/alternative-probability-measure.jpg" alt="Alternative Probability Measure" /></p>
<p>I have noted that this technique can benefit client libraries and apps to enhance their own quality. Also, companies that offer comunication through APIs, in order to improve their own quality, should encourage client designers to use techniques like these.</p>
<p>Cheers,<br>
Rafael.</p>
</description>
</item>
<item>
<title>Speeding up your MongoDB queries up to 30 times with Tornado</title>
<link>https://rafaelcapucho.github.io/2016/09/speeding-up-your-mongodb-queries-up-to-30-times-with-tornado/</link>
<pubDate>Mon, 05 Sep 2016 00:00:00 UTC</pubDate>
<author>Rafael Capucho</author>
<guid>https://rafaelcapucho.github.io/2016/09/speeding-up-your-mongodb-queries-up-to-30-times-with-tornado/</guid>
<description>
<p>Sometime ago, I was facing a <em>problem</em> using MongoDB to perform heavy operations like Aggregations over a considerable amount of documents.</p>
<p>Fortunately, most of them were repeating, like when your projects are fetching contents from database to make the same menu structure, it doesn&rsquo;t change every second.</p>
<p>We already know how is the recipe to solve that: <strong>Cache it</strong>.</p>
<p>I was using <a href="http://www.tornadoweb.org">Tornado</a> and it&rsquo;s common to use <a href="https://github.com/mongodb/motor">Motor</a> to perform async database operations over MongoDB. The idea was to implement a Mixin that can be used in all handlers and support the three most common operations to get data:</p>
<ol>
<li>Find</li>
<li>Find One</li>
<li>Aggregate</li>
</ol>
<p>Ok, let&rsquo;s do it.</p>
<h2 id="establishing-the-connection">Establishing the connection</h2>
<p>We won&rsquo;t need a lot of stuffs here, just the boilerplate.</p>
<pre><code class="language-python">import logging
import motor
from pymongo.errors import ConnectionFailure
from tornado.options import define, options
define(&quot;mongo_host&quot;, default=&quot;mongodb://localhost:27017&quot;, help=&quot;mongodb://user:pass@localhost:27017&quot;)
define(&quot;mongo_db&quot;, default=&quot;database_name&quot;)
def create_connection():
try:
return motor.MotorClient(options.mongo_host)[options.mongo_db]
except ConnectionFailure:
logging.error('Could not connect to Mongo DB. Exit')
exit(1)
return False
</code></pre>
<p>Now we&rsquo;re able to establish the connection and the object will be available through <code>self.application.db</code> in every handler. Other aspects of the code like imports are omitted.</p>
<pre><code class="language-python">class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r&quot;/?&quot;, MainHandler),
]
self.db = create_connection()
tornado.web.Application.__init__(self, handlers)
http_server = tornado.httpserver.HTTPServer(Application())
http_server.bind(options.port)
http_server.start(1)
main_loop = tornado.ioloop.IOLoop.instance()
main_loop.start()
</code></pre>
<h2 id="the-mixin-code">The Mixin Code</h2>
<p>With the connection available, it&rsquo;s our Mixin time.</p>
<pre><code class="language-python">#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from hashlib import md5
import datetime
import tornado.web
from tornado import gen
from tornado.options import define, options
from handlers import DBMixin
define(&quot;cache&quot;, default=&quot;True&quot;, type=bool, help=&quot;Enable/Disable the internal cache&quot;)
_cache = {}
class DBMixin(object):
@property
def db(self): return self.application.db
class CacheHandler(tornado.web.RequestHandler, DBMixin):
def __init__(self, *args, **kwargs):
super(CacheHandler, self).__init__(*args, **kwargs)
self.FIND_ONE = 1
self.FIND = 2
self.AGGREGATE = 3
@gen.coroutine
def cache(self, type, col, *args, **kwargs):
memory = kwargs.pop('memory', True) # Local Memory (Ram)
timeout = kwargs.pop('timeout', 60)
sort = kwargs.pop('sort', None)
# Union of every input
signature = str(type)+col+str(args)+str(kwargs)
# Generate a unique key
key = md5(signature.encode('utf-8')).hexdigest()
@gen.coroutine
def get_key(key):
if not options.cache:
raise gen.Return(False)
if memory:
if _cache.get(key, False):
raise gen.Return(_cache[key])
else:
raise gen.Return(False)
else:
data = yield self.db['_cache'].find_one({'key': key})
raise gen.Return(data)
@gen.coroutine
def set_key(key, value):
delta = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
if memory:
_cache[key] = {
'd': value,
't': delta
}
else:
yield self.db['_cache'].insert({
'key': key,
'd': value,
't': delta
})
@gen.coroutine
def del_key(key):
if memory:
if _cache.get(key, False): del _cache[key]
else:
yield self.db['_cache'].remove({'key': key})
_key = yield get_key(key)
if _key:
# If the time in the future is still bigger than now
if _key['t'] &gt;= datetime.datetime.now():
raise gen.Return(_key['d'])
else: # Invalid
yield del_key(key)
# otherwise (key not exist)
if type == self.FIND_ONE:
data = yield self.db[col].find_one(*args, **kwargs)
elif type == self.FIND:
if sort:
cursor = self.db[col].find(*args, **kwargs).sort(sort)
else:
cursor = self.db[col].find(*args, **kwargs)
data = yield cursor.to_list(kwargs.pop('to_list', None))
elif type == self.AGGREGATE:
cursor = self.db[col].aggregate(
kwargs.pop('pipeline', []),
*args,
cursor = kwargs.pop('cursor', {}),
**kwargs
)
data = yield cursor.to_list(kwargs.pop('to_list', None))
if options.cache:
# Persist the key
yield set_key(key, data)
raise gen.Return(data)
</code></pre>
<h2 id="how-it-works">How it works?</h2>
<p>The code is simple, basically we can use Local Memory or a MongoDB table as cache, and we are able to choose which one of them by setting the argument <code>memory</code>.</p>
<p>Also, your handler should be using our Mixin, as in the example.</p>
<pre><code class="language-python">class MainHandler(tornado.web.RequestHandler, CacheHandler):
@gen.coroutine
def get(self):
category = yield find_category_by_slug('electronic-gadgets')
self.render('index.html', {'category': category})
@gen.coroutine
def find_category_by_slug(self, slug, filters={}):
defaults = {'slug': slug}
defaults.update(filters)
category = yield self.cache(
self.FIND_ONE, # Type of query
'categories', # Name of the document
defaults, # Conditions
memory=True, # Store on python memory
timeout=3600 # Expire in 1 hour
)
raise gen.Return(category)
@gen.coroutine
def find_categories(self, slug, filters={}):
categories = yield self.cache(
self.FIND, # Type of query
'categories', # Name of the document
filters, # Conditions
sort = [('order', 1)], # Sort Criteria
memory = False, # Store on db table
timeout = 86400, # Expire in 1 day
to_list=50 # Return up to 50 items
)
raise gen.Return(categories)
@gen.coroutine
def complex_aggregation(self, category, sort, limit):
pipeline = [
{'$match':
{'cats_ids': {'$all': [ ObjectId(category['_id']) ]}}
},
{'$project':
{'products': 1, 'min_price': 1, 'max_price': 1, 'n_products': 1, '_id': 1}
},
{'$sort': sort },
{'$skip': self.calculate_page_skip(limit=limit)},
{'$limit': limit}
]
groups = yield self.cache(
self.AGGREGATE, # Type of query
'products_groups', # Name of the document
memory=False, # Store on db table
pipeline=pipeline # Operations
)
raise gen.Return(groups)
</code></pre>
<p>As you can see, there are always an opportunity to enhance the performance.</p>
<p><a href="https://gist.github.com/rafaelcapucho/571a5ce63bc0fb0d4c43b445324ae58c">Download the Gist</a></p>
<h3 id="how-can-i-know-if-it-worth-the-price">How can I know if it worth the price?</h3>
<p>It doesn&rsquo;t count if you don&rsquo;t see it, right? Ok, lets measure it.</p>
<pre><code class="language-python">#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import time
class Timer(object):
def __init__(self, verbose=False, desc=&quot;&quot;):
self.verbose = verbose
self.desc = desc
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 # millisecs
if self.verbose:
if self.desc:
print('Time elapsed of {0} - '.format(self.desc), end=&quot;&quot;)
print('{0:f} ms'.format(self.msecs))
</code></pre>
<p>Now we are able to test it.</p>
<pre><code class="language-python">with Timer(True, desc='getting the category with cache') as t:
category = yield self.cache(self.FIND_ONE, 'categories', {'slug':'cars'}, memory=True)
with Timer(True, desc='getting the category without cache') as t:
category = yield self.db.categories.find_one({'slug': 'cars'})
</code></pre>
<p>I&rsquo;m pretty sure that you will see the spent time near to 0ms with the cache.</p>
<p>Cheers,<br />
Rafael.</p>
</description>
</item>
</channel>
</rss>