|
| 1 | +--- |
| 2 | +title: Timeouts |
| 3 | +current_menu: timeouts |
| 4 | +introduction: Configure and handle timeouts. |
| 5 | +--- |
| 6 | + |
| 7 | +When a Lambda function times out, it is like the power to the computer is suddenly |
| 8 | +just turned off. This does not give the application a chance to shutdown properly. |
| 9 | +This often leaves you without any logs and the problem could be hard to fix. |
| 10 | + |
| 11 | +Bref will throw an `LambdaTimeout` exception just before the Lambda actually times |
| 12 | +out. This will allow your application to actually shutdown. |
| 13 | + |
| 14 | +This feature is enabled automatically for the `php-xx` layer and the `console` layer. |
| 15 | +The `php-xx-fpm` layer needs to opt-in by adding the following to `index.php`. |
| 16 | + |
| 17 | +```php |
| 18 | +if (isset($_SERVER['LAMBDA_TASK_ROOT'])) { |
| 19 | + \Bref\Timeout\Timeout::enable(); |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +## Configuration |
| 24 | + |
| 25 | +You may configure this behavior with the `BREF_TIMEOUT` environment variable. To |
| 26 | +always trigger an exception after 10 seconds, set `BREF_TIMEOUT=10`. To disable |
| 27 | +Bref throwing an exception use value `BREF_TIMEOUT=-1`. To automatically set the |
| 28 | +timeout just a hair shorter than the Lambda timeout, use `BREF_TIMEOUT=0`. |
| 29 | + |
| 30 | +## Catching the exception |
| 31 | + |
| 32 | +If you are using a framework, then the framework is probably catching all exceptions |
| 33 | +and displays an error page for the users. You may of course catch the exception |
| 34 | +yourself: |
| 35 | + |
| 36 | +```php |
| 37 | +<?php |
| 38 | + |
| 39 | +require dirname(__DIR__) . '/vendor/autoload.php'; |
| 40 | + |
| 41 | +use Bref\Context\Context; |
| 42 | +use Bref\Timeout\LambdaTimeout; |
| 43 | + |
| 44 | +class Handler implements \Bref\Event\Handler |
| 45 | +{ |
| 46 | + public function handle($event, Context $context) |
| 47 | + { |
| 48 | + try { |
| 49 | + $this->generateResponse(); |
| 50 | + } catch (LambdaTimeout $e) { |
| 51 | + echo 'Oops, sorry. We spent too much time on this.'; |
| 52 | + } catch (\Throwable $e) { |
| 53 | + echo 'Some unexpected error happened.'; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + private function generateResponse() |
| 58 | + { |
| 59 | + $pi = // ... |
| 60 | + echo 'Pi is '.$pi; |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +return new Handler(); |
| 65 | +``` |
0 commit comments