Skip to content

Latest commit

 

History

History
134 lines (97 loc) · 8.58 KB

UsingTheConnectionLifetimePlugin.md

File metadata and controls

134 lines (97 loc) · 8.58 KB

Connection Lifetime Plugin

The Connection Lifetime Plugin limits how long the AWS Advanced Python Wrapper uses a physical database connection. When an expired connection is about to make a network-bound call, the plugin either closes the connection or reconnects to the host originally supplied by the application.

Enabling the Connection Lifetime Plugin

Add the plugin code connection_lifetime to the plugins parameter. The connection_lifetime_ms parameter is required.

params = {
    "host": "db-identifier.cluster-XYZ.us-east-2.rds.amazonaws.com",
    "dbname": "postgres",
    "user": "username",
    "password": "password",
    "plugins": "connection_lifetime",
    "connection_lifetime_ms": 300000
}

conn = AwsWrapperConnection.connect(psycopg.Connection.connect, **params)

Unless auto_sort_wrapper_plugin_order is set to False, the Connection Lifetime Plugin automatically runs before every other plugin.

Configuration Parameters

Parameter Value Required Description Default Value
connection_lifetime_ms int Yes Maximum physical connection lifetime in milliseconds. The value must be a whole number of at least 1. None
connection_lifetime_action str No Action taken after the connection expires. Accepted values are reconnect and close, ignoring case and surrounding spaces. reconnect

A missing or invalid connection_lifetime_ms value, or an unsupported connection_lifetime_action value, raises an AwsWrapperError when the connection is opened.

Expiration Checks

The lifetime starts when a physical connection is created. A connection the plugin did not see being created, for example one opened while the plugin was skipped, is timestamped when the plugin first notices it. A connection is expired when its elapsed lifetime is greater than or equal to connection_lifetime_ms. The boundary is inclusive, so a connection with a configured lifetime of 1000 ms is expired at exactly 1000 ms.

The plugin checks the lifetime immediately before the calls the driver dialect marks as network-bound, such as:

  • Connection.cursor, Connection.commit and Connection.rollback
  • Cursor.execute, Cursor.callproc and the Cursor.fetch* methods
  • reading or setting autocommit and read_only

It does not run a background timer. An expired connection therefore stays open until the next network-bound call triggers the configured action.

Connection.close, Cursor.close and the closed-state check never trigger the action, so an expired connection can always be closed.

The plugin applies only to the connection used by the application. Internal connections opened by other plugins, such as monitoring or topology connections, have their own lifecycle and are not tracked.

The configured action runs before the pending call, and the pending call is not executed.

Close Action

With connection_lifetime_action set to close, the plugin closes the current physical connection and raises a ConnectionLifetimeExpiredError. If closing the connection fails, the failure is available as the error's __cause__.

The wrapper connection remains permanently unusable after this error, and every later network-bound call raises ConnectionLifetimeExpiredError. Close the wrapper connection and open a new one.

Reconnect Action

With the default connection_lifetime_action of reconnect, the plugin opens a replacement physical connection to the host and port the application originally supplied. It does not use a host selected later by read/write splitting, failover or another plugin. The replacement becomes the wrapper connection's current connection, and the lifetime is reset only after that switch succeeds.

After a successful reconnect, the plugin raises a ConnectionLifetimeSuccessError. The wrapper connection already holds the replacement connection, but the pending call was not executed. Re-create any cursors, reconfigure any session state that is not transferred automatically, and retry the operation.

ConnectionLifetimeSuccessError does not extend FailoverSuccessError. Application code that retries after a successful failover must also catch ConnectionLifetimeSuccessError to retry after a successful reconnect.

If opening or installing the replacement connection fails, the plugin raises a ConnectionLifetimeFailedError, with the original failure available as its __cause__. The lifetime is not reset, so the next network-bound call tries to reconnect again. If the replacement was installed but the switch did not complete, the plugin closes both connections and later network-bound calls raise ConnectionLifetimeExpiredError.

Transactions

Neither action runs while a transaction is active. If the lifetime expires during a transaction, network-bound calls continue on the current physical connection, so commit and rollback complete normally. Deferral does not extend or reset the lifetime.

After the transaction ends, the first network-bound call runs the configured action before that call.

Error Handling

Error Connection Usable Afterwards SQLSTATE What To Do
ConnectionLifetimeSuccessError Yes 08S02 Re-create cursors, reconfigure session state if required and retry the pending operation.
ConnectionLifetimeFailedError Not always 08001 Retry later, or close the connection and open a new one if the error is repeated.
ConnectionLifetimeExpiredError No 08003 Close the connection and open a new one.

All three errors are defined in aws_advanced_python_wrapper.errors and extend ConnectionLifetimeError, which extends AwsWrapperError and OperationalError. Catch ConnectionLifetimeError to handle every lifetime outcome in one place, or check the subclasses to tell them apart.

from aws_advanced_python_wrapper.errors import (
    ConnectionLifetimeExpiredError, ConnectionLifetimeFailedError,
    ConnectionLifetimeSuccessError)

try:
    cursor = conn.cursor()
    cursor.execute("SELECT 1")
except ConnectionLifetimeSuccessError:
    # The connection now holds a new physical connection. Re-create the cursor and retry.
    cursor = conn.cursor()
    cursor.execute("SELECT 1")
except ConnectionLifetimeFailedError:
    # The replacement connection could not be opened. Retry later, or open a new connection.
    ...
except ConnectionLifetimeExpiredError:
    # The connection was closed. Open a new connection.
    ...

The asynchronous wrapper raises the same errors.

Connection Pooling

The plugin measures the lifetime of the connection held by one wrapper connection. With internal connection pooling through SqlAlchemyPooledConnectionProvider or the asynchronous pooled connection provider, the lifetime is measured from the time the connection was taken from the pool rather than from the time the physical connection was opened. When the plugin closes or replaces an expired pooled connection, it evicts the connection first, so the pool closes the physical connection instead of handing it out again. A connection taken from the pool may already be older than connection_lifetime_ms. A connection that a read/write splitting plugin keeps cached is not evicted while it is cached. It keeps its creation time, so if the application switches back to it after it has expired, the configured action runs on it, and a reconnect goes to the host the application originally supplied rather than to the reader. To bound the age of pooled physical connections, use the pool's own settings, such as SQLAlchemy's pool_recycle.

With SQLAlchemy, the wrapper dialects treat ConnectionLifetimeSuccessError as a usable connection and the other lifetime errors as a disconnect, so the pool invalidates a connection that cannot be used again.