A Database Credential Lease Is Also a Connection-Pool Contract

·

10 min read

A database password can expire while the process that obtained it continues to run. A connection pool can remain healthy even when the next connection attempt is destined to fail. These observations describe different lifetimes, and a platform that treats them as a single clock results in predictable operational failure.

Dynamic credentials change how database access is issued. They do not automatically change how application libraries retain connections, retry transactions, or replace authentication material. The platform contract therefore has to extend from the Vault lease into the workload's connection lifecycle.

This historical design study uses the database and lease interfaces documented in Vault 1.18.0, which was officially released in October 2024, before the March 2026 editorial cutoff. It does not depend on later agent identity features or managed-service capabilities. The version identifies the evidence baseline, not a recommended production patch level. Versioned release.

Two lifetimes meet at the connection boundary

Vault's database secrets engine generates credentials from a configured role and associates dynamic credentials with leases. The database plugin performs the database-specific creation and revocation work. A static role is different: it maps to an existing database username and rotates that account's password. Those models should not be combined under an unspecified “rotating secret” abstraction. Archived database documentation.

A dynamic role is useful when a platform wants an identifiable credential generation for a workload instance or bounded unit of work. Its database permissions still come from the configured creation statements and role design. A short lifetime does not compensate for excessive SQL privileges.

The connection pool introduces another lifecycle. Its connections may have been authenticated using an earlier credential generation. Its stored configuration controls future connection creation. Changing that configuration does not, by itself, establish that existing sessions have ended or that every borrower has switched.

The important boundary is therefore not “password updated”. It is “new work is admitted only through a generation with sufficient remaining lifetime, while older connections are drained according to an explicit policy”. That is a proposed platform contract, not a feature automatically supplied by Vault.

Renewal is an observation, not a promise

A lease response contains an identifier, duration and renewability information. A renewal request can ask for an increment, but the requested increment is advisory. The returned duration determines the new observed deadline; adding the requested number to the old deadline would implement a different contract. Revoking a parent token also affects leases created through it. Archived lease semantics.

The credential manager should keep both the latest successful observation and the time it was received. Its working deadline is calculated from that observation, with a safety margin for scheduling and transport uncertainty. A failed renewal leaves the previously observed deadline in place. It does not justify inventing another interval of validity.

That rule creates a useful operational distinction. A service can still have time to replace credentials after renewal fails. The failure becomes an early transition to replacement work rather than an immediate application outage or an excuse to continue indefinitely.

The remaining lifetime also needs to be compared with the work being admitted. A five-second query and a long-running export do not place the same demand on a pool. A fixed “credential is not yet expired” check can admit work that is unlikely to complete within the intended access window.

Put credential management outside the reasoning loop

An AI-assisted worker may decide which approved analysis to perform, but it does not need the database password in its model context. A bounded execution service can own the pool and expose a smaller operation such as reading an approved report.

That separation is a design choice. Vault alone cannot prevent an application from copying a returned password into a prompt, debug message, or tool response. The platform must define the data returned from the execution service and limit the model's ability to change the credential-management policy.

The same distinction applies to renewal. A model can explain why a worker is draining, but the lease manager should own deadlines, retries, and generation changes. Natural-language reasoning is not a reliable substitute for a monotonic admission rule.

Proposed design: the lease manager controls new connection admission, the pool drains the previous generation, and the workload receives operation results rather than credentials.

A small executable admission model

The following complete example models the handover decision. It does not authenticate to Vault or PostgreSQL, and it does not emulate a database driver's connection pool. Times and generation identifiers are synthetic. The purpose is to make the acceptance rules inspectable before writing an adapter.

from dataclasses import dataclass

@dataclass(frozen=True)
class Generation:
    name: str
    expires_at: int
    ready: bool
    revoked: bool = False

def admit(generation, now, work_budget, safety_margin):
    return (
        generation is not None
        and generation.ready
        and not generation.revoked
        and work_budget >= 0
        and safety_margin >= 0
        and now + work_budget + safety_margin < generation.expires_at
    )

def select(current, replacement, now, work_budget, safety_margin):
    if replacement is not None and admit(
        replacement, now, work_budget, safety_margin
    ):
        return replacement.name, "SWITCH_AND_DRAIN"
    if admit(current, now, work_budget, safety_margin):
        return current.name, "KEEP"
    return None, "HOLD"

old = Generation("g1", expires_at=160, ready=True)
new = Generation("g2", expires_at=300, ready=True)
assert select(old, None, 100, 20, 10) == ("g1", "KEEP")
assert select(old, new, 100, 20, 10) == ("g2", "SWITCH_AND_DRAIN")
assert select(old, None, 130, 20, 10) == (None, "HOLD")
print("Admission examples passed")

The strict inequality intentionally rejects work at the safety boundary. That is a conservative choice for this model, not a documented database requirement. The safety margin and work budget need workload-specific values supported by operational evidence.

The replacement must be ready before selection. Readiness represents a successful bounded connection check under the new credential. Merely receiving a username and password does not prove that the role's SQL statements produced usable permissions or that the application can reach the database.

The action SWITCH_AND_DRAIN also has limited meaning. It instructs a real implementation to stop opening old-generation connections and begin draining existing borrowers. It is not an assertion that a transaction can be interrupted without consequences. Database behavior and driver semantics require their own integration tests.

The handover needs durable ownership

A production pool adapter needs a single owner for generation changes. If multiple workers independently decide to replace the same shared credential, the platform can create overlapping generations without a reliable account of which process uses which one.

A useful record contains the workload identity, lease identifier, credential-generation reference, observed deadline and handover state. The credential value should be kept in the smallest practical runtime boundary. Operational dashboards normally need the reference and state rather than the secret.

The handover can be divided into preparation, activation and retirement. Preparation obtains the replacement and verifies a new connection. Activation updates the source used for new connections. Retirement waits for the agreed drain condition, then reconciles the old generation.

Those stages should not be collapsed into a single successful function return. A process can fail after activating the replacement but before retiring the old lease. Recovery then needs to discover the actual active generation and resume cleanup, rather than blindly acquiring a third credential.

For a shared pool, the active-generation update also needs concurrency control. A compare-and-swap against the previous generation prevents a delayed replacement attempt from overwriting a newer successful handover. This is ordinary controller state management, independent of Vault's secret-generation API.

Revocation and session termination are separate questions

Vault's PostgreSQL integration exposes database-specific statements and behavior through its plugin interface. Its configuration has to be reviewed together with database permissions and the selected plugin version. A generic lease abstraction cannot prove how an already authenticated SQL session behaves when a database role is changed or removed. Archived PostgreSQL integration, PostgreSQL API reference.

The safe engineering position is to test both fresh authentication and established sessions. A revocation test that only attempts a new connection can miss a still-active old session. A test that only observes a pool exception can miss an account that remains usable elsewhere.

A containment runbook may require terminating sessions in addition to revoking the lease. That operation can interrupt transactions, so its owner and consequences need to be explicit. An orderly rotation and an emergency revocation should not share an undocumented assumption that every in-flight operation will finish.

Likewise, a temporary database outage can prevent cleanup from completing. The platform should distinguish the request to revoke from confirmed database-side cleanup. Repeatedly deleting local records would make the dashboard look cleaner while removing the information needed to reconcile the remaining account.

Avoid coupling every request to Vault

Issuing a credential for every application request may appear maximally isolated, but it also moves account creation and lease management into the request path. That creates load, operational churn and another failure dependency.

At the other extreme, sharing one credential across an entire fleet reduces attribution and increases the number of consumers affected by a replacement. The allocation unit should reflect the workload's trust boundary and operational model: a job, a worker instance or a deliberately shared service pool.

There is no universal allocation interval. The choice should consider transaction duration, connection establishment cost, pool size, database account limits and the desired containment scope. These are architecture trade-offs to measure, not numbers inferable from the existence of a default TTL.

A platform interface can hide those mechanics from application teams while still exposing meaningful states: healthy, replacement preparing, draining and blocked. A single “secret available” indicator omits the information needed to diagnose an approaching access deadline.

Test the failure boundary before tuning the interval

The accompanying local checks exercise the admission predicate with missing, unready, revoked and expired generations; a valid replacement; an unready replacement; a boundary-time rejection; and invalid negative budgets. These are tests of original control logic only.

An integration suite needs more: renewal returning less time than requested, database unavailability during credential creation, a failed readiness query, a borrower that never returns its connection, a process restart during handover and an old session after revocation. Test fixtures should include the exact role statements and driver configuration used by the service.

The SQL privileges of the Vault management account deserve separate review. The database API distinguishes connection configuration from dynamic role definitions, and the management identity must be able to perform the intended account operations. Granting it broad database authority merely to make a demonstration work would hide a material part of the security design. Archived database API.

A reconnect storm deserves its own test. If many workers observe the same deadline and replace credentials together, the database and Vault can receive a concentrated burst of creation and authentication work. Staggered renewal and bounded replacement concurrency are proposed mitigations, but they must not extend a credential's validity beyond the last observed lease.

The admission controller should also distinguish unavailable capacity from invalid authority. A ready replacement with a full pool may justify waiting within a request deadline. An expired generation should not be selected simply because it has spare connections. Combining both conditions into a generic retry loop makes it difficult to enforce the security boundary under load.

Operational ownership can be made explicit in the platform contract. The service team owns transaction budgets and acceptable drain behavior. The platform team owns lease observation, credential handling and pool-generation coordination. The database owner validates account permissions and session termination behavior. This division avoids assigning every failure to the team that happens to operate Vault.

A useful developer-facing error can then say that new database work is paused while a replacement generation is validated, without disclosing a username or password. The message explains the affected capability and recovery state. It does not promise that a failed transaction was rolled back or that an old session was terminated. Those outcomes require database-specific evidence.

Dynamic credentials are most useful when their lifetime becomes part of the workload contract. The result is not just a password that changes. It is a controlled transition between generations, with bounded admission, observable draining and enough durable evidence to recover when the database, Vault or the worker fails independently.