Connection Pooling and Reuse
What you'll learn: How to reuse database connections and HTTP clients across multiple serverless function invocations to dramatically reduce overhead and improve performance.
The Core Idea
In traditional servers, you establish connections to databases or external services once and reuse them for many requests. In serverless functions, each invocation could create new connections, which is expensive—especially database connections that require authentication, TLS handshakes, and network round-trips.
The solution? Place your connection objects in global scope (outside your handler function). When the execution context is reused for warm starts, those connections persist and can be reused instantly.
How It Works
Think of it like a phone call. Every time you need to talk to someone, you could hang up and redial (expensive). Or you could keep the line open between conversations when you know you'll talk again soon (efficient).
# BAD: Creates new connection every invocation
def handler(event, context):
db_connection = create_database_connection()
result = db_connection.query("SELECT * FROM users")
return result
# GOOD: Reuses connection across invocations
db_connection = None
def handler(event, context):
global db_connection
if db_connection is None:
db_connection = create_database_connection()
result = db_connection.query("SELECT * FROM users")
return result
The first approach creates a fresh connection every time—slow and wasteful. The second creates it once, then reuses it on warm invocations. You check if the connection exists; if not, establish it. If it does, use it immediately.
This applies to HTTP clients, database pools, and any resource with initialization overhead.
Key Takeaway: Place expensive connections in global scope to reuse them across warm function invocations, dramatically reducing latency and resource consumption.