summaryrefslogtreecommitdiff
path: root/pod/lua-resty-limit-traffic-0.09/resty.limit.conn.pod
blob: 5d8ccbb7b53d3b967467a5c9169f867a3bd16a83 (plain)
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
=encoding utf-8


=head1 Name

resty.limit.conn - Lua module for limiting request concurrency (or concurrent connections) for OpenResty/ngx_lua.


=head1 Synopsis


    # demonstrate the usage of the resty.limit.conn module (alone!)
    http {
        lua_shared_dict my_limit_conn_store 100m;
    
        server {
            location / {
                access_by_lua_block {
                    -- well, we could put the require() and new() calls in our own Lua
                    -- modules to save overhead. here we put them below just for
                    -- convenience.
    
                    local limit_conn = require "resty.limit.conn"
    
                    -- limit the requests under 200 concurrent requests (normally just
                    -- incoming connections unless protocols like SPDY is used) with
                    -- a burst of 100 extra concurrent requests, that is, we delay
                    -- requests under 300 concurrent connections and above 200
                    -- connections, and reject any new requests exceeding 300
                    -- connections.
                    -- also, we assume a default request time of 0.5 sec, which can be
                    -- dynamically adjusted by the leaving() call in log_by_lua below.
                    local lim, err = limit_conn.new("my_limit_conn_store", 200, 100, 0.5)
                    if not lim then
                        ngx.log(ngx.ERR,
                                "failed to instantiate a resty.limit.conn object: ", err)
                        return ngx.exit(500)
                    end
    
                    -- the following call must be per-request.
                    -- here we use the remote (IP) address as the limiting key
                    local key = ngx.var.binary_remote_addr
                    local delay, err = lim:incoming(key, true)
                    if not delay then
                        if err == "rejected" then
                            return ngx.exit(503)
                        end
                        ngx.log(ngx.ERR, "failed to limit req: ", err)
                        return ngx.exit(500)
                    end
    
                    if lim:is_committed() then
                        local ctx = ngx.ctx
                        ctx.limit_conn = lim
                        ctx.limit_conn_key = key
                        ctx.limit_conn_delay = delay
                    end
    
                    -- the 2nd return value holds the current concurrency level
                    -- for the specified key.
                    local conn = err
    
                    if delay >= 0.001 then
                        -- the request exceeding the 200 connections ratio but below
                        -- 300 connections, so
                        -- we intentionally delay it here a bit to conform to the
                        -- 200 connection limit.
                        -- ngx.log(ngx.WARN, "delaying")
                        ngx.sleep(delay)
                    end
                }
    
                # content handler goes here. if it is content_by_lua, then you can
                # merge the Lua code above in access_by_lua into your
                # content_by_lua's Lua handler to save a little bit of CPU time.
    
                log_by_lua_block {
                    local ctx = ngx.ctx
                    local lim = ctx.limit_conn
                    if lim then
                        -- if you are using an upstream module in the content phase,
                        -- then you probably want to use $upstream_response_time
                        -- instead of ($request_time - ctx.limit_conn_delay) below.
                        local latency = tonumber(ngx.var.request_time) - ctx.limit_conn_delay
                        local key = ctx.limit_conn_key
                        assert(key)
                        local conn, err = lim:leaving(key, latency)
                        if not conn then
                            ngx.log(ngx.ERR,
                                    "failed to record the connection leaving ",
                                    "request: ", err)
                            return
                        end
                    end
                }
            }
        }
    }


=head1 Description

This module provides APIs to help the OpenResty/ngx_lua user programmers limit request
concurrency levels.

If you want to use multiple different instances of this class at once or use one instance
of this class with instances of other classes (like L<resty.limit.req|./req.md>),
then you I<must> use the L<resty.limit.traffic|./traffic.md> module to combine them.

In contrast with NGINX's standard
L<ngx_limit_conn|http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html> module,
this Lua module supports connection delaying in addition to immediate rejection when the
concurrency level threshold is exceeded.


=head1 Methods




=head2 new

B<syntax:> C<obj, err = class.new(shdict_name, conn, burst, default_conn_delay)>

Instantiates an object of this class. The C<class> value is returned by the call C<require "resty.limit.conn">.

This method takes the following arguments:


=over


=item *

C<shdict_name> is the name of the
L<lua_shared_dict|https://github.com/openresty/lua-nginx-module#lua_shared_dict> shm zone.

It is best to use separate shm zones for different kinds of limiters.

=item *

C<conn> is the maximum number of concurrent requests allowed. Requests exceeding this ratio (and below C<conn> + C<burst>)
will get delayed to conform to this threshold.

=item *

C<burst> is the number of excessive concurrent requests (or connections) allowed to be
delayed.

Requests exceeding this hard limit should get rejected immediately.

=item *

C<default_conn_delay> is the default processing latency of a typical connection (or request).

This delay is used as a basic unit for the extra delay introduced for excessive concurrent requests (or connections),
which can later get adjusted dynamically by the subsequent L<leaving> method
calls in L<log_by_lua*|https://github.com/openresty/lua-nginx-module#log_by_lua>.


=back

On failure, this method returns C<nil> and a string describing the error (like a bad C<lua_shared_dict> name).




=head2 incoming

B<syntax:> C<delay, err = obj:incoming(key, commit)>



Fires a new concurrent request (or new connection) incoming event and
calculates the delay needed (if any) for the current request
upon the specified key or whether the user should reject it immediately.

This method accepts the following arguments:


=over


=item *

C<key> is the user specified key to limit the concurrency level.

For example, one can use the host name (or server zone)
as the key so that we limit concurrency per host name. Otherwise, we can also use the client address as the
key so that we can avoid a single client from flooding our service with too many parallel connections or requests.

Please note that this module
does not prefix nor suffix the user key so it is the user's responsibility to ensure the key
is unique in the C<lua_shared_dict> shm zone).

=item *

C<commit> is a boolean value. If set to C<true>, the object will actually record the event
in the shm zone backing the current object; otherwise it would just be a "dry run" (which is the default).


=back

The return values depend on the following cases:


=over


=item 1.

If the request does not exceed the C<conn> value specified in the L<new> method, then
this method returns C<0> as the delay as well as the number of concurrent
requests (or connections) at the current time (as the 2nd return value).

=item 2.

If the request (or connection) exceeds the C<conn> limit specified in the L<new> method but not
the C<conn> + C<burst> value, then
this method returns a proper delay (in seconds) for the current request so that it still conform to
the C<conn> threshold as if it came a bit later rather than now.

In addition, like the previous case, this method
also returns a second return value indicating the number of concurrent requests (or connections)
at this point (including the current request). This 2nd return value can be used to monitor the
unadjusted incoming concurrency level.

=item 3.

If the request exceeds the C<conn> + C<burst> limit, then this method returns C<nil> and
the error string C<"rejected">.

=item 4.

If an error occurred (like failures when accessing the C<lua_shared_dict> shm zone backing
the current object), then this method returns C<nil> and a string describing the error.


=back

This method does not sleep itself. It simply returns a delay if necessary and requires the caller
to later invoke the L<ngx.sleep|https://github.com/openresty/lua-nginx-module#ngxsleep>
method to sleep.

This method must be paired with a L<leaving> method call typically in the
L<log_by_lua*|https://github.com/openresty/lua-nginx-module#log_by_lua> context if
and only if this method actually records the event in the shm zone (designated by
a subsequent L<is_committed> method call.


=head2 is_committed

B<syntax:> C<bool = obj:is_committed()>

Returns C<true> if the previous L<incoming> call actually commits the event
into the C<lua_shared_dict> shm store; returns C<false> otherwise.

This result is important in that one should only pair the L<leaving> method call
with a L<incoming> call
if and only if this C<is_committed> method call returns C<true>.




=head2 leaving

B<syntax:> C<conn = obj:leaving(key, req_latency?)>

Fires an event that the current request (or connection) is being finalized. Such events
essentially reduce the current concurrency level.

This method call usually pairs with an earlier L<incoming> call unless
the L<is_committed> call returns C<false> after that L<incoming> call.

This method takes the following parameters:


=over


=item *

C<key> is the same key string used in the paired L<incoming> method call.

=item *

C<req_latency> is the actual latency of the current request (or connection), which is optional.

Often we use the value of either the C<$request_time> or C<$upstream_response_time> nginx builtin variables here. One can, of course, record the latency himself.


=back

The method returns the new concurrency level (or number of active connections). Unlike
L<incoming>, this method always commits the changes to the shm zone.




=head2 set_conn

B<syntax:> C<obj:set_conn(conn)>

Overwrites the C<conn> threshold value as specified in the L<new> method.




=head2 set_burst

B<syntax:> C<obj:set_burst(burst)>

Overwrites the C<burst> threshold value as specified in the L<new> method.




=head2 uncommit

B<syntax:> C<ok, err = obj:uncommit(key)>

This tries to undo the commit of the C<incoming> call. This method is mainly for being used in the L<resty.limit.traffic|./traffic.md>
Lua module when combining multiple limiters at the same time.

This method should not be used replace of the L<leaving> method though they are
similar in effect and implementation.




=head1 Caveats




=head2 Out-of-Sync Counter Prevention

Under extreme conditions, like nginx worker processes crash in the middle of request processing,
the counters stored in the shm zones can go out of sync. This can lead to catastrophic
consequences like blindly rejecting I<all> the incoming connections for ever. (Note that
the standard C<ngx_limit_conn> module also suffers from this issue.) We may
add automatic protection for such cases to this Lua module in the near future.

Also, it is very important to ensure that the C<leaving> call appears first in your
C<log_by_lua*> handler code to minimize the chance that other C<log_by_lua*> Lua code
throws out an exception and prevents the C<leaving> call from running.




=head1 Instance Sharing

Each instance of this class carries no state information but the C<conn> and C<burst>
threshold values. The real limiting states based on keys are stored in the C<lua_shared_dict>
shm zone specified in the L<new> method. So it is safe to share instances of
this class L<on the nginx worker process level|https://github.com/openresty/lua-nginx-module#data-sharing-within-an-nginx-worker>
as long as the combination of C<conn> and C<burst> do not change.

Even if the C<conn> and C<burst>
combination I<does> change, one can still share a single instance as long as he always
calls the L<set_conn> and/or L<set_burst> methods I<right before>
the L<incoming> call.




=head1 Limiting Granularity

The limiting works on the granularity of an individual NGINX server instance (including all
its worker processes). Thanks to the shm mechanism; we can share state cheaply across
all the workers in a single NGINX server instance.

If you are running multiple NGINX server instances (like running multiple boxes), then
you need to ensure that the incoming traffic is (more or less) evenly distributed across
all the different NGINX server instances (or boxes). So if you want a limit of N connections
across all the servers, then you just need to specify a limit of C<N/n> in each server's configuration. This simple strategy can save all the (big) overhead of sharing a global state across
machine boundaries.




=head1 Installation

Please see L<library installation instructions|../../../README.md#installation>.




=head1 Community




=head2 English Mailing List

The L<openresty-en|https://groups.google.com/group/openresty-en> mailing list is for English speakers.




=head2 Chinese Mailing List

The L<openresty|https://groups.google.com/group/openresty> mailing list is for Chinese speakers.




=head1 Bugs and Patches

Please report bugs or submit patches by


=over


=item 1.

creating a ticket on the L<GitHub Issue Tracker|https://github.com/openresty/lua-resty-limit-traffic/issues>,

=item 2.

or posting to the L<OpenResty community>.


=back




=head1 Author

Yichun "agentzh" Zhang (章亦春) E<lt>agentzh@gmail.comE<gt>, CloudFlare Inc.




=head1 Copyright and License

This module is licensed under the BSD license.

Copyright (C) 2015-2016, by Yichun "agentzh" Zhang, CloudFlare Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:


=over


=item *

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.


=back


=over


=item *

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.


=back

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.




=head1 See Also


=over


=item *

module L<resty.limit.req|./req.md>

=item *

module L<resty.limit.count|./count.md>

=item *

module L<resty.limit.traffic|./traffic.md>

=item *

library L<lua-resty-limit-traffic|../../../README.md>

=item *

the ngx_lua module: https://github.com/openresty/lua-nginx-module

=item *

OpenResty: https://openresty.org/


=back