Connection Pooling Sample Code

Find out about some particularly efficient connection pooling sample code to consider adding to functions you create with OCI Functions.

For functions that connect to external resources, you will typically want to include connection pooling code in a function to reduce the time required to establish a connection when the function is invoked for the first time.

This section shows you some particularly efficient connection pooling sample code.

Python Example of Connection Pooling Code

import requests, json, logging

def send_to_endpoint(data: list, rest_endpoint: str):
    """
    This function demonstrates best practices to efficiently POST data payloads to REST API endpoints.
    Because the Session and HTTPAdapter negotiate and retain TLS sessions with endpoints for the life of 
    the connection pool, it eliminates expensive TLS re-negotiation per POST.
    """

    session = None

    try:
        session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(pool_connections=10, pool_maxsize=10)
        session.mount('https://', adapter)
        http_headers = {'Content-type': 'application/json'}

        for item in data:
            resp = session.post(rest_endpoint, data=json.dumps(item), headers=http_headers)
            if resp.status_code not in [200, 202]:
                raise RuntimeError(f'POST Error / {resp.status_code} / {resp.text}')
            logging.info(f'POST Success / {resp.status_code} / {resp.text}')

    finally:
        session.close()