PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/docs/service/dynamodb-session-handler.rst

https://gitlab.com/github-cloud-corp/aws-sdk-php
ReStructuredText | 242 lines | 184 code | 58 blank | 0 comment | 0 complexity | 02321c3e35759416c9648709f93653a4 MD5 | raw file
  1. ========================
  2. DynamoDB Session Handler
  3. ========================
  4. Introduction
  5. ------------
  6. The **DynamoDB Session Handler** is a custom session handler for PHP that
  7. allows developers to use Amazon DynamoDB as a session store. Using DynamoDB
  8. for session storage alleviates issues that occur with session handling in a
  9. distributed web application by moving sessions off of the local file system and
  10. into a shared location. DynamoDB is fast, scalable, easy to setup, and handles
  11. replication of your data automatically.
  12. The DynamoDB Session Handler uses the ``session_set_save_handler()`` function
  13. to hook DynamoDB operations into PHP's `native session functions <http://www.php.net/manual/en/ref.session.php>`_
  14. to allow for a true drop in replacement. This includes support for features like
  15. session locking and garbage collection which are a part of PHP's default
  16. session handler.
  17. For more information on the Amazon DynamoDB service, please visit the
  18. `Amazon DynamoDB homepage <http://aws.amazon.com/dynamodb>`_.
  19. Basic Usage
  20. -----------
  21. 1. Register the handler
  22. ~~~~~~~~~~~~~~~~~~~~~~~
  23. The first step is to instantiate and register the session handler.
  24. .. code-block:: php
  25. use Aws\DynamoDb\SessionHandler;
  26. $sessionHandler = SessionHandler::fromClient($dynamoDb, [
  27. 'table_name' => 'sessions'
  28. ]);
  29. $sessionHandler->register();
  30. 2. Create a table for storing your sessions
  31. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  32. Before you can actually use the session handler, you need to create a table in
  33. which to store the sessions. This can be done ahead of time through the
  34. `AWS Console for Amazon DynamoDB <https://console.aws.amazon.com/dynamodb/home>`_,
  35. or using the SDK.
  36. 3. Use PHP sessions like normal
  37. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38. Once the session handler is registered and the table exists, you can write to
  39. and read from the session using the ``$_SESSION`` superglobal, just like you
  40. normally do with PHP's default session handler. The DynamoDB Session Handler
  41. encapsulates and abstracts the interactions with Amazon DynamoDB and enables
  42. you to simply use PHP's native session functions and interface.
  43. .. code-block:: php
  44. // Start the session
  45. session_start();
  46. // Alter the session data
  47. $_SESSION['user.name'] = 'jeremy';
  48. $_SESSION['user.role'] = 'admin';
  49. // Close the session (optional, but recommended)
  50. session_write_close();
  51. Configuration
  52. -------------
  53. You may configure the behavior of the session handler using the following
  54. options. All options are optional, but you should make sure to understand
  55. what the defaults are.
  56. ``table_name``
  57. The name of the DynamoDB table in which to store the sessions. This defaults to ``'sessions'``.
  58. ``hash_key``
  59. The name of the hash key in the DynamoDB sessions table. This defaults to ``'id'``.
  60. ``session_lifetime``
  61. The lifetime of an inactive session before it should be garbage collected. If it is not provided, then the actual
  62. lifetime value that will be used is ``ini_get('session.gc_maxlifetime')``.
  63. ``consistent_read``
  64. Whether or not the session handler should use consistent reads for the ``GetItem`` operation. This defaults
  65. to ``true``.
  66. ``locking``
  67. Whether or not to use session locking. This defaults to ``false``.
  68. ``batch_config``
  69. Configuration used to batch deletes during garbage collection. These options are passed directly into `DynamoDB
  70. WriteRequestBatch <http://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.DynamoDb.WriteRequestBatch.html>`_ objects.
  71. You must manually trigger garbage collection via ``SessionHandler::garbageCollect()``.
  72. ``max_lock_wait_time``
  73. Maximum time (in seconds) that the session handler should wait to acquire a lock before giving up. This defaults
  74. to ``10`` and is only used with session locking.
  75. ``min_lock_retry_microtime``
  76. Minimum time (in microseconds) that the session handler should wait between attempts to acquire a lock. This
  77. defaults to ``10000`` and is only used with session locking.
  78. ``max_lock_retry_microtime``
  79. Maximum time (in microseconds) that the session handler should wait between attempts to acquire a lock. This
  80. defaults to ``50000`` and is only used with session locking.
  81. To configure the Session Handler, you must specify the configuration options when you instantiate the handler. The
  82. following code is an example with all of the configuration options specified.
  83. .. code-block:: php
  84. $sessionHandler = SessionHandler::fromClient($dynamoDb, [
  85. 'table_name' => 'sessions',
  86. 'hash_key' => 'id',
  87. 'session_lifetime' => 3600,
  88. 'consistent_read' => true,
  89. 'locking' => false,
  90. 'batch_config' => [],
  91. 'max_lock_wait_time' => 10,
  92. 'min_lock_retry_microtime' => 5000,
  93. 'max_lock_retry_microtime' => 50000,
  94. ]);
  95. Pricing
  96. -------
  97. Aside from data storage and data transfer fees, the costs associated with using Amazon DynamoDB are calculated based on
  98. the provisioned throughput capacity of your table (see the `Amazon DynamoDB pricing details
  99. <http://aws.amazon.com/dynamodb/pricing/>`_). Throughput is measured in units of Write Capacity and Read Capacity. The
  100. Amazon DynamoDB homepage says:
  101. A unit of read capacity represents one strongly consistent read per second (or two eventually consistent reads per
  102. second) for items as large as 4 KB. A unit of write capacity represents one write per second for items as large as
  103. 1 KB.
  104. Ultimately, the throughput and the costs required for your sessions table is going to correlate with your expected
  105. traffic and session size. The following table explains the amount of read and write operations that are performed on
  106. your DynamoDB table for each of the session functions.
  107. +-------------------------------------+-----------------------------------------------------------------------------+
  108. | Read via ``session_start()`` | * 1 read operation (only 0.5 if ``consistent_read`` is ``false``). |
  109. | | * (Conditional) 1 write operation to delete the session if it is expired. |
  110. +-------------------------------------+-----------------------------------------------------------------------------+
  111. | Read via ``session_start()`` | * A minimum of 1 *write* operation. |
  112. | (Using session locking) | * (Conditional) Additional write operations for each attempt at acquiring a |
  113. | | lock on the session. Based on configured lock wait time and retry options.|
  114. | | * (Conditional) 1 write operation to delete the session if it is expired. |
  115. +-------------------------------------+-----------------------------------------------------------------------------+
  116. | Write via ``session_write_close()`` | * 1 write operation. |
  117. +-------------------------------------+-----------------------------------------------------------------------------+
  118. | Delete via ``session_destroy()`` | * 1 write operation. |
  119. +-------------------------------------+-----------------------------------------------------------------------------+
  120. | Garbage Collection | * 0.5 read operations **per 4 KB of data in the table** to scan for expired |
  121. | | sessions. |
  122. | | * 1 write operation **per expired item** to delete it. |
  123. +-------------------------------------+-----------------------------------------------------------------------------+
  124. .. _ddbsh-session-locking:
  125. Session Locking
  126. ---------------
  127. The DynamoDB Session Handler supports pessimistic session locking in order to mimic the behavior of PHP's default
  128. session handler. By default the DynamoDB Session Handler has this feature *turned off* since it can become a performance
  129. bottleneck and drive up costs, especially when an application accesses the session when using ajax requests or iframes.
  130. You should carefully consider whether or not your application requires session locking or not before enabling it.
  131. To enable session locking, set the ``'locking'`` option to ``true`` when you instantiate the ``SessionHandler``.
  132. .. code-block:: php
  133. $sessionHandler = SessionHandler::fromClient($dynamoDb, [
  134. 'table_name' => 'sessions',
  135. 'locking' => true,
  136. ]);
  137. .. _ddbsh-garbage-collection:
  138. Garbage Collection
  139. ------------------
  140. The DynamoDB Session Handler supports session garbage collection by using a series of ``Scan`` and ``BatchWriteItem``
  141. operations. Due to the nature of how the ``Scan`` operation works and in order to find all of the expired sessions and
  142. delete them, the garbage collection process can require a lot of provisioned throughput.
  143. For this reason, we do not support automated garbage collection . A better practice is to schedule the garbage
  144. collection to occur during an off-peak time where a burst of consumed throughput will not disrupt the rest of the
  145. application. For example, you could have a nightly cron job trigger a script to run the garbage collection. This script
  146. would need to do something like the following:
  147. .. code-block:: php
  148. $sessionHandler = SessionHandler::fromClient($dynamoDb, [
  149. 'table_name' => 'sessions',
  150. 'batch_config' => [
  151. 'batch_size' => 25,
  152. 'before' => function ($command) {
  153. echo "About to delete a batch of expired sessions.\n";
  154. }
  155. ]
  156. ]);
  157. $sessionHandler->garbageCollect();
  158. You can also use the ``'before'`` option within ``'batch_config'`` to introduce delays on the ``BatchWriteItem``
  159. operations that are performed by the garbage collection process. This will increase the amount of time it takes the
  160. garbage collection to complete, but it can help you spread out the requests made by the session handler in order to
  161. help you stay close to or within your provisioned throughput capacity during garbage collection.
  162. .. code-block:: php
  163. $sessionHandler = SessionHandler::fromClient($dynamoDb, [
  164. 'table_name' => 'sessions',
  165. 'batch_config' => [
  166. 'before' => function ($command) {
  167. $command['@http']['delay'] = 5000;
  168. }
  169. ]
  170. ]);
  171. $sessionHandler->garbageCollect();
  172. Best Practices
  173. --------------
  174. #. Create your sessions table in a region that is geographically closest to or in the same region as your application
  175. servers. This will ensure the lowest latency between your application and DynamoDB database.
  176. #. Choose the provisioned throughput capacity of your sessions table carefully, taking into account the expected traffic
  177. to your application and the expected size of your sessions.
  178. #. Monitor your consumed throughput through the AWS Management Console or with Amazon CloudWatch and adjust your
  179. throughput settings as needed to meet the demands of your application.
  180. #. Keep the size of your sessions small (ideally less than 1 KB). Small sessions will perform better and require less
  181. provisioned throughput capacity.
  182. #. Do not use session locking unless your application requires it.
  183. #. Instead of using PHP's built-in session garbage collection triggers, schedule your garbage collection via a cron job,
  184. or another scheduling mechanism, to run during off-peak hours. Use the ``'batch_config'`` option to your advantage.